8

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.

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).

4

2 回答 2

13

为此,您可以使用选项ticks.userCallback中的 ,scales.xAxes以便为每个 xaxis 刻度返回格式化的日期。如果您使用的是 bundle 版本,则 chartjs 附带了 momentjs,这使得它非常容易,但如果您只是以毫秒为单位传递时间戳,您可以对标签执行任何您想要的操作。

options: {
    scales: {
        xAxes: [{
            ticks: {
                userCallback: function(label, index, labels) {
                    return moment(label).format("DD/MM/YY");
                }
             }
        ]}
     }
 }

小提琴https://jsfiddle.net/leighking2/q5ak7p3h/

于 2016-08-05T14:57:39.413 回答
3

3.4版你可以这样做:

 options: {
        scales: {
            x: {
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value;
                    }
                }
            }
        }
    }
于 2021-06-29T05:43:07.410 回答