在chart.js中为多轴折线图使用自定义数据格式

问题描述 投票:0回答:1

我从服务器获得的数据作为响应格式如下:

   [
            {
                "date": "2019-03-04T14:59:35.000Z",
                "data1": 21.739999771118164,
                "data2": 57.72999954223633
            },
            {
                "date": "2019-03-04T14:59:42.000Z",
                "data1": 21.739999771118164,
                "data2": 57.72999954223633
            },
            {
                "date": "2019-03-04T14:59:50.000Z",
                "data1": 21.729999542236328,
                "data2": 57.7400016784668
            }
]

如何使用此数据格式创建带有chart.js的多轴折线图?

javascript json format chart.js
1个回答
0
投票

使用示例qazxsw opi,您可以尝试稍微更改它,并找到如下所示的内容:

上面的代码打印:var json = [ { "date": "2019-03-04T14:59:35.000Z", "data1": 21.739999771118164, "data2": 57.72999954223633 }, { "date": "2019-03-04T14:59:42.000Z", "data1": 21.739999771118164, "data2": 57.72999954223633 }, { "date": "2019-03-04T14:59:50.000Z", "data1": 21.729999542236328, "data2": 57.7400016784668 }]; var labels = json.map(i => i.date); var dataset1 = json.map(i => i.data1); var dataset2 = json.map(i => i.data2); let renderChart = function () { var ctx = document.getElementById('canvas').getContext('2d'); new Chart(ctx, { "type": "line", "data": { "labels": labels, "datasets": [ { "label": "Dataset1", "data": dataset1, "fill": false, "borderColor": "rgb(75, 192, 192)", "lineTension": 0.1, yAxisID: "y-axis-1", }, { "label": "Dataset2", "data": dataset2, "fill": false, "borderColor": "rgb(0, 192, 255)", "lineTension": 0.2, yAxisID: "y-axis-2", }] }, "options": { responsive: false, hoverMode: 'index', stacked: false, title: { display: true, text: 'Multi Axis' }, scales: { yAxes: [{ type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, position: "left", id: "y-axis-1", }, { type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, position: "right", id: "y-axis-2", // grid line settings gridLines: { drawOnChartArea: false, // only want the grid lines for one axis to show up }, }], } } }); }

© www.soinside.com 2019 - 2024. All rights reserved.