Modifying the X-Axis Labels of a Scatterplot in Chart.js 2
Asked Answered
D

2

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

Dorton answered 4/8, 2016 at 20:47 Comment(1)
Can you provide an example of desired format? Also, provide an example of your current format.Overland
A
12

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");
                }
             }
        ]}
     }
 }

fiddle https://jsfiddle.net/leighking2/q5ak7p3h/

Agamete answered 5/8, 2016 at 14:57 Comment(1)
Is it any parameter for fixed x-axes and Y-axes, As I have used it dynamically and when our dataset is changed Axes for the graph also reflected.Gecko
I
3

version 3.4 you can do it something like this:

 options: {
        scales: {
            x: {
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value;
                    }
                }
            }
        }
    }
Izy answered 29/6, 2021 at 5:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.