I am generating a highchart using json that is created by PHP. Everything is working perfectly fine. However I can't figure out how do I make the series dynamic in the following code? :
$.getJSON("myFile.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
In the above code, there are only 2 series. However I do not know how many series will be present as they will change according to user request. Can someone please tell me how to make this part dynamic:
options.series[0] = json[1];
options.series[1] = json[2];
Thanks in advance :)
$.each(json, function( index, value ) {
options.series[index-1] = value;
});
Be careful to start your json to 1 if you want series from 0 to n
Try this
$.getJSON("myFile.php", function(json) {
options.xAxis.categories = json[0]['data'];
for (var i = 0; i < options.series.length; i++) {
options.series[i] = json[i + 1];
}
chart = new Highcharts.Chart(options);
});
Related
My Chart JS always failed to showing labels or legends when the data is from ajax response, The data is showing up but the legend always failed, I created my labels manually and assign it one by one but it's still doesn't work and ended up with error like Uncaught TypeError: Cannot read property 'fontSize' of undefined, but when i change the chart type to pie or doughnut, my chart is working but still the legends or labels is not showing up.
here's my code :
function getChartData() {
$.ajax({
dataType: 'JSON',
method: 'POST',
cache: false,
url: '<?php base_url()?>/Rest_API/someurl',
}).done(function(data){
var timeseries = data['result']['timeseries'];
var d1 = timeseries['0']['uniques']['all'];
var d2 = timeseries['1']['uniques']['all'];
var d3 = timeseries['2']['uniques']['all'];
var d4 = timeseries['3']['uniques']['all'];
var d5 = timeseries['4']['uniques']['all'];
var d6 = timeseries['5']['uniques']['all'];
var d7 = timeseries['6']['uniques']['all'];
var l1 = timeseries['0']['since']
var l2 = timeseries['1']['since']
var l3 = timeseries['2']['since']
var l4 = timeseries['3']['since']
var l5 = timeseries['4']['since']
var l6 = timeseries['5']['since']
var l7 = timeseries['6']['since']
var chartdata = [d1,d2,d3,d4,d5,d6,d7];
var chartlabels = [l1,l2,l3,l4,l5,l6,l7]
//Create the chart.js data structure using 'labels' and 'data'
var tempData = {
labels : chartlabels,
datasets : [{
data : chartdata
}]
};
var ctx = document.getElementById("chartPageRequest").getContext('2d');
var myLineChart = new Chart(ctx).Line(tempData, {
});
});
}
<div class="GrafikchartPageRequest">
<canvas id="chartPageRequest"></canvas>
</div>
and just for testing, I change my data and label manually inside the ajax done function like above :
var tempData = {
labels : ["1","2","3","4"],
datasets : [{
data : [4,5,6,7]
}]
};
var ctx = document.getElementById("chartPageRequest").getContext('2d');
var myLineChart = new Chart(ctx).Line(tempData, {
});
but still thrown an error Uncaught TypeError: Cannot read property 'fontSize' of undefined that's mean the legends is failed to showing up. Thank you.
UPDATE : AJAX RESPONSE
I am working in Planet Press Connect. I have created a dynamic bar chart and now I need to add labels to the data. Can anyone help me. I am a beginner in java script so not sure what to do. Below is the code I have. this creates what I need except the labels.
if (results.length) {
// The data-chartdata attribute only holds the key value pairs of the data
var chartData = [];
function addValueToSeries(labelField, valueField) {
var temp = {};
temp['value_label'] = record.fields[labelField];
// Number of series is dynamic, add a value to each series
for (var i = 0; i < record.tables['Age'].length; i++) {
temp['values_' + (i+1)] = record.tables['Age'][i].fields[valueField];
}
chartData.push(temp);
}
addValueToSeries('pls_Age2', 'pls_ageAvg');
results.attr('data-chartData', JSON.stringify(chartData));
// Connect the series to the values
var series = [];
for (var i = 0; i < record.tables['Age'].length; i++) {
series[i] = { 'title' : record.tables['Age'][i].fields['pls_ageAvg'],
'valueField' : 'values_' + (i+1) };
}
var graphsData = { 'categoryField' : 'value_label', 'graphs' : series };
results.attr('data-graphsdata', JSON.stringify(graphsData));
}
My zingchart's last element's color does not match with legend, and keeps on changing unlike the others. Any Ideas? Everything else works good. Though I'm parsing this data through MySQL database, this is how the JavaScript looks like.
My code:
<script>
var myData = ["12","15","7","20","2","22","10","7","7","10","8","15","9"];
var myData = myData.map(parseFloat);
var myLabels = ["General Verbal Insults","General Beatings\/Pushing","Terrorizing\/Threatening Remarks","False Gossip Inflation (Rumors)","Discrimination","Rough Fighting","Sexual Utterance\/Assaults","General Exclusion","Theft","Racist Utterance\/Assaults","Personal Property Damage","Internet Related (Cyber)","Other\/Unspecified"];
window.onload=function(){
var colorCharacters = "ACDEF0123456789";
var globalStylesArray = [];
var myConfig = {
type: "bar",
legend:{},
title: {
"text":"Showing Results For: Canada",
"color":"green"
},
subtitle: {
"text":"Total Bullying Incidents In Country: 144",
"color":"blue"
},
series : [{"values":[ myData[0] ],"text":"General Verbal Insults",},{"values":[ myData[1] ],"text":"General Beatings/Pushing",},{"values":[ myData[2] ],"text":"Terrorizing/Threatening Remarks",},{"values":[ myData[3] ],"text":"False Gossip Inflation (Rumors)",},{"values":[ myData[4] ],"text":"Discrimination",},{"values":[ myData[5] ],"text":"Rough Fighting",},{"values":[ myData[6] ],"text":"Sexual Utterance/Assaults",},{"values":[ myData[7] ],"text":"General Exclusion",},{"values":[ myData[8] ],"text":"Theft",},{"values":[ myData[9] ],"text":"Racist Utterance/Assaults",},{"values":[ myData[10] ],"text":"Personal Property Damage",},{"values":[ myData[11] ],"text":"Internet Related (Cyber)",},{"values":[ myData[12] ],"text":"Other/Unspecified",}]
};
zingchart.render({
id : 'myChart',
data : myConfig,
width:"100%",
height:500,
});
zingchart.gload = function(p) {
console.log(p);
var graphId = p.id;
var graphData = {};
graphData = zingchart.exec(graphId, 'getdata');
graphData = graphData.graphset[0] ? graphData.graphset[0] : graphData;
console.log(graphData);
createColors(graphData.series[0].values.length);
zingchart.exec(graphId, 'modifyplot', {
data: {
styles: globalStylesArray
}
});
}
function createColors(seriesLength) {
console.log('-------createColor seriesLength: ', seriesLength);
globalStylesArray = [];
for (var i = 0; i < seriesLength; i++) {
var colorString = '#';
for (var j = 0; j < 6; j++) {
colorString += colorCharacters.charAt(Math.floor(Math.random() * (colorCharacters.length - 4)));
}
globalStylesArray.push(colorString);
}
console.log('-----globalStylesArray-------', globalStylesArray);
}
};
</script>
Referring to the comment on the OP:
I just want all color to be different, since i dont know how many elements are in MyData - its generated through PHP & MYSQL
If you just want all of the colors to be different, remove the zingchart.gload function and the createColors function. ZingChart will create different colors for each series dynamically.
If you do want to specify each of those colors ahead of time since you do not know how many series your data will produce, you will need to apply a theme to your chart configuration: http://www.zingchart.com/docs/design-and-styling/javascript-chart-themes/
I need to assign a javascript variable to amcharts dataloader. but following code does not work (Graph does not draw)
AmCharts.ready(function () {
var data = [{"employee_no": "101","Salary": "1000"},{"employee_no": "102","Salary": "1500"},{"employee_no": "103","Salary": "1100"},{"employee_no": "104","Salary": "1900"},{"employee_no": "105","Salary": "1200"},
{"employee_no": "106","Salary": "1800"},{"employee_no": "107","Salary": "2000"},{"employee_no": "108","Salary": "1500"}];
var chart = new AmCharts.AmSerialChart();
chart.dataLoader = data;
chart.categoryField = "employee_no";
var graph = new AmCharts.AmGraph();
graph.valueField = "Salary";
graph.type = "line";
graph.bullet = "round";
graph.lineColor = "#8d1cc6";
chart.addGraph(graph);
chart.write('chartdiv');
});
but if I use below code it works fine.
chart.dataLoader = {
url: "MY_URL",
postProcess: function (data, options) {
if (data === null) {
data = [];
options.chart.addLabel("50%", "50%", "No Data Available");
}
return data;
}
};
What is the error of above code ? I cannot figure it out.
Thanks you
Thank you martynasma, You are right
I have to use chart.dataProvider instead of chart.dataLoader
That solved my problem. We have to use chart.dataLoader only with http request.
I'm using Flot Charts to plot the data and I am facing a strange problem. At each iteration, the plot area gets smaller, in the images attached this can be seen. I will post the function I'm using to plot to make it easier to understand or to locate the error.
<script type="text/javascript">
$(document).ready(function () {
var xVal = 0;
var data3 = [[],[]];
var dataset4=<?php echo json_encode($dataset4); ?>;
var dataset5=<?php echo json_encode($dataset5); ?>;
var totallength = dataset4.length;
var options3 = {
};
var plot = $.plot( $("#placeholder3"), data3, options3);
var yVal1 = [];
var yVal2 = [];
function getData(){
yVal1 = parseFloat(dataset5[xVal]);
//yVal2 = parseFloat(dataset5[xVal +1]);
var datum1 = [parseFloat(dataset4[xVal]), yVal1];
//var datum2 = [parseFloat(dataset4[xVal + 1]), yVal2];
data3[0].push(datum1);
//data3[1].push(datum2);
if(data[0].length>10){
data3[0] = data3[0].splice(1);
//data3[1] = data3[1].splice(1);
}
xVal++;
plot.setData(data3);
plot.setupGrid();
if(xVal<=totallength){
plot.draw();
}
}
var plot = $.plot( $("#placeholder3"), data3, options3);
setInterval(getData, 1000);
});
</script>
Maybe the error is at the setupGrid, or at the plot.draw... I just don't know. Thanks for your time in advance!
It seems that moving the plot action inside the if statement where I had the plot.draw() solved it. Now the plot area remains stable and plots properly.