簡體   English   中英

如何使用JSON數據創建CanvasJS圖表?

[英]How do I create a CanvasJS Chart using JSON data?

我創建了一個測試圖,它工作正常。 我想通過Ajax來獲取數據,而不是將其嵌入網頁中。 我認為需要格式化dataPoints數組( { x: new Date(2009, 0), y: 15 }, 2009,0 { x: new Date(2009, 0), y: 15 }, ),以便可以在外部JSON文件中使用它們。 在我的示例中,填充我的圖表的數據格式為:

我的JSChart小提琴示例

{
  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 }
  ]
},

我查看了Canvas JS網站,他們使用了以下Ajax調用示例:

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

不知道這是否有所不同,但是上述AJAX調用中使用的JSON數據格式為:

[[1,12],[2,7],[3,6],[4,6],[5,9],[6,13],[7,12],[8,15],[9,14],[10,18]]

編輯
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

查看canvasJS的文檔,該示例要求您將數據格式化為以下格式: {x: valueX, y: valueY}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM