问题描述
在Chart.js 2中,我生成一个散点图,其中x坐标是Epoch时间戳,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方法格式化那些日期(例如,2016年8月5日星期五)。
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刻度的日期。如果您正在使用捆绑版本,则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");
}
}
]}
}
}
小提琴
这篇关于修改Chart.js中Scatterplot的X轴标签2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!