循环在canvasjs中创建折线图

Loop to create lines chart in canvasjs

我有一个数组对象:

  total = 
   [
    {
      date: 5/12/2017,
      count: 5,
      type: A
     },
     {
      date: 5/15/2017,
      count: 15,
      type: A
     },
     {
      date: 5/12/2017,
      count: 4,
      type: B
     },
     {
      date: 5/15/2017,
      count: 5,
      type: C
     }..
    ]

我想知道如何使用 CanvasJS 在折线图中循环显示它们,每条线表示每种类型,x 轴表示日期,y 轴表示计数

这是我目前的情况:

     var chart = new CanvasJS.Chart("chartContainer",
        {
            title: {
                text: "My Counts"
            },
            axisX: {
                title: "Date",
            },
            axisY: {
                title: "Count"
            },
            data: []
           });

您可以 运行 对数组进行 for 循环并将数据点存储在不同的变量中,以便稍后在图表中使用它。

var dps1 = [];
var dps2 = [];
var dps3 = [];

for(var i = 0; i < total.length; i++) {
    if(total[i].type === "A") {
        dps1.push({x: new Date(total[i].date), y: total[i].count});
    } else if(total[i].type === "B") {
        dps2.push({x: new Date(total[i].date), y: total[i].count});
    } else if(total[i].type === "C") {
        dps3.push({x: new Date(total[i].date), y: total[i].count});
    }
}

存储数据点后,您需要在图表中使用它。

data: [{
    type: "line",
    dataPoints: dps1
}, {
    type: "line",
    dataPoints: dps2
}, {
    type: "line",
    dataPoints: dps3
}]