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 轴标签


基础教程推荐
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01