循环以在canvasjs中创建折线图

时间:2017-05-17 19:15:04

标签: javascript charts 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: []
           });

1 个答案:

答案 0 :(得分:2)

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

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

存储dataPoints后,您需要在图表中使用它。

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