在 Chart.js 2 中修改散点图的 X 轴标签
在 Chart.js 2 中,我生成了一个散点图,其中 x 坐标是纪元时间戳,y 坐标是整数.我想知道是否有办法格式化图表的 x 轴标签,以便日期以人类可读的格式显示.
In Chart.js 2 I am generating a scatter-plot where there x coordinates are Epoch timestamps and the y coordinates are integers. I was wondering if there was a way to format the x-axis labels of the graph, so that the dates are displayed in a human-readable format.
更新:目前我正在以毫秒为单位从 Unix 时间戳构建图表.此原型的其他部分使用 Date 类的 toDateString 方法格式化这些日期(例如,Fri Aug 5 2016).
Update: Currently I am building my graph from Unix timestamps in milliseconds. The other parts of this prototype format those dates with the toDateString method of the Date class (eg. Fri Aug 5 2016).
推荐答案
为此,您可以使用 scales.xAxes
选项中的 ticks.userCallback
以便您为每个 xaxis 刻度返回一个格式化的日期.如果您使用的是 bundle 版本,chartjs 附带了 momentjs,这使得它非常容易,但如果您只是以毫秒为单位传递时间戳,您可以对标签执行任何您想要的操作.
For this you can make use of the ticks.userCallback
in the scales.xAxes
option so that you return a formatted date for each xaxis tick. If you are using the bundle version chartjs comes with momentjs which makes it really easy but if you are just passing timestamps in milliseconds you can do whatever you want to the label.
options: {
scales: {
xAxes: [{
ticks: {
userCallback: function(label, index, labels) {
return moment(label).format("DD/MM/YY");
}
}
]}
}
}
小提琴 https://jsfiddle.net/leighking2/q5ak7p3h/
相关文章