在 Chart.js 2 中修改散点图的 X 轴标签 [英] Modifying the X-Axis Labels of a Scatterplot in Chart.js 2

查看:32
本文介绍了在 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 轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆