问题
I am new to amcharts and I am using the below code to generate two graphs in a chart.
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"dataLoader": {
"url": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/218423/data1.json"
},
"valueAxes": [{
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
}],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [{
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits"
}],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "country",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
}
});
function setDataSet(dataset_url) {
AmCharts.loadFile(dataset_url, {}, function(data) {
chart.dataProvider = AmCharts.parseJSON(data);
chart.validateData();
});
So this works perfectly and now instead of one graph I want to add multiple graphs in the chart.But I do not want to Define before how many graphs I need(No fixed size).So how to dynamically add graphs in amcharts?Any help is appreciated
回答1:
Assuming you already know the categoryField upfront, you can use dataLoader's complete
callback to look at your newly assigned dataProvider
array and create graphs based on the keys in the array object.
"dataLoader": {
"url": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/SO-41015973.json",
"complete": function(chart) {
//get potential valueFields after filtering out the categoryField
var valueFields = Object.keys(chart.dataProvider[0]).filter(function(value) {
return value !== chart.categoryField;
});
//create the graphs
valueFields.forEach(function(valueField) {
chart.graphs.push({
"valueField": valueField,
"type": "column",
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillAlphas": 0.8,
"lineAlphas": 0.2
})
});
}
},
I added an extra field to your data and created a codepen demo to show that this works.
来源:https://stackoverflow.com/questions/41015973/how-to-add-multiple-graphs-in-amcharts