I'm trying to render a scatter plot in chart.js of (x,y) data where x is a date string. I've seen many examples and tutorials online where the instructor uses a function to generate the time stamp for an example chart, but I haven't found any examples that use real data like one might collect.
I have data that looks like this (collected from cron):
2017-07-08T06:15:02-0600,23.375
2017-07-08T06:20:02-0600,23.312
2017-07-08T06:25:02-0600,23.312
2017-07-08T06:30:02-0600,23.25
I tried a data like this in chart.js (both with and without "quotes" around the data string):
data: [{
x: 2017-07-08T06:15:02-0600,
y: 23.375
},{
x: 2017-07-08T06:20:02-0600,
y: 23.312
},{
x: 2017-07-08T06:25:02-0600,
y: 23.312
},{
x: 2017-07-08T06:30:02-0600,
y: 23.25
}],
Nothing renders. What am I doing wrong?
3条答案
按热度按时间wd2eg0qa1#
According to the documentation of scatter charts:
Unlike the line chart where data can be supplied in two different formats, the scatter chart only accepts data in a point format.
So you can't use values like
2017-07-08T06:15:02-0600
. You can convert dates into numbers and use them in your data.In your case:
Now your xAxes will be with numbers, so you can use a
callback
to modify xAxes labels.g52tjvyc2#
这个建议并不完全正确。javascript moment.js允许使用日期作为x轴值来绘制散点数据。由于某种原因,Chart.bundle.js中的捆绑版本对我不起作用,所以我直接下载了moment.js。我用它来设置:
下面是chart.js数据的详细信息:
效果很好!
ifsvaxew3#
Another solution that worked great for me, was to just use the
line
type for the chart, configure it for using dates for the x axis, and addtionally disable the lines, so that it just looks like a scatterplot.I see this as a quite elegant solution. The documentation even specifies:
The scatter chart supports all of the same properties as the line chart. By default, the scatter chart will override the showLine property of the line chart to false.