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 轴标签
基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
