如何使用JSON数据创建CanvasJS图表?

时间:2017-06-27 03:34:55

标签: javascript jquery json canvasjs

我创建了一个测试图表,它运行正常。我想通过ajax获取我的数据,而不是嵌入网页。我想我需要格式化我的dataPoints数组(CKOwnerDefaultName),以便它们可以在外部JSON文件中使用。在我的示例中,填充我的图表的数据格式为:

My JSChart Fiddle Example

{ x: new Date(2009, 0), y: 15 },

我查看了Canvas JS站点,他们使用了以下Ajax调用示例:

{
  name: "File Sharing",
  showInLegend: true,
  type: "stackedColumn100",
  color: "#4192D9 ",
  indexLabel: "{y}",
  dataPoints: [
    { x: new Date(2009, 0), y: 15 },
    { x: new Date(2010, 0), y: 15 },
    { x: new Date(2011, 0), y: 12 },
    { x: new Date(2012, 0), y: 10 },
    { x: new Date(2013, 0), y: 12 },
    { x: new Date(2014, 0), y: 10 }
  ]
},

不确定这是否有所不同,但上面AJAX调用中使用的JSON数据的格式为:

var dataPoints = []; $.getJSON("https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=100&type=json", function(data) { $.each(data, function(key, value){ dataPoints.push({x: value[0], y: parseInt(value[1])}); }); var chart = new CanvasJS.Chart("chartContainer",{ title:{ text:"Rendering Chart with dataPoints from External JSON" }, data: [{ type: "line", dataPoints : dataPoints, }] }); chart.render(); });

1 个答案:

答案 0 :(得分:6)

修改
https://jsfiddle.net/uvac6rdz/2/
使用已编辑的数据格式来匹配OP的首选axisX。

var chart = new CanvasJS.Chart("chartContainer", {
  title: {
    text: "Composition of Internet Traffic in North America",
    horizontalAlign: "right"
  },
  axisX: {
    tickThickness: 0,
    interval: 1,
    intervalType: "year"
  },
  animationEnabled: true,
  toolTip: {
    shared: true
  },
  axisY: {
    lineThickness: 0,
    tickThickness: 0,
    interval: 20
  },
  legend: {
    verticalAlign: "center",
    horizontalAlign: "left"
  },

  data: [
  {
    name: "Real-Time",
    showInLegend: true,
    type: "column",
    color: "#004B8D ",
    indexLabel: "{y}",
    dataPoints: [
    { x: new Date(2009,0), y: 12 },
    { x: new Date(2010,0), y: 7 },
    { x: new Date(2011,0), y: 6}, 
    { x: new Date(2012,0), y: 6}, 
    { x: new Date(2013,0), y: 9}, 
    { x: new Date(2014,0), y: 13}, 
    { x: new Date(2015,0), y: 12}, 
    { x: new Date(2016,0), y: 15}, 
    { x: new Date(2017,0), y: 14}
    ]
  },

  ]
});

chart.render();

我更改了以下内容:

  1. axisX.intervalType"year""number"的类型 (由于您的样本数据)。

  2. 将您的样本数据格式化为[[1,12],[2,7]...以遵循
    [{x: 1, y: 12}, {x: 2, y: 7},...

  3. stackedColumn100column的图表类型。

  4. 查看canvasJS的文档,该示例要求您格式化要遵循的数据: {x: valueX, y: valueY}