如何在amcharts中添加多个图形

时间:2016-12-07 11:13:29

标签: javascript amcharts

我是amcharts的新手,我使用下面的代码在图表中生成两个图表。

 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();
  });

所以这个工作完美,现在而不是一个图形我想在图表中添加多个图形。但我不想在我需要多少图形之前定义(没有固定大小)。那么如何在amcharts中动态添加图形?感谢任何帮助

1 个答案:

答案 0 :(得分:1)

假设您已经预先知道categoryField,您可以使用dataLoader的complete回调来查看新分配的dataProvider数组,并根据数组对象中的键创建图形。 / p>

  "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
        })
      });
    }
  },

我在您的数据中添加了一个额外的字段,并创建了一个codepen demo来表明这是有效的。