Modifying the X-Axis Labels of a Scatterplot in Chart.js 2(在 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/
这篇关于在 Chart.js 2 中修改散点图的 X 轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Chart.js 2 中修改散点图的 X 轴标签


基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01