Highchart datetime axis formatting
If you have worked with Highcharts, you know that it’s sometimes difficult to find all the right incantations to get it to do your biding.
One that particularly stumped me was the datetime axis type. I had regular data, for example some metric per month, with my points having an X value of the first day of each month. At first, everything seems fine:
The problem
So far, so good. But then, you add a date format for the labels, because your client doesn’t like Highcharts’ default format:
Furthermore, your client complains that sometimes the labels repeat themselves when he generates the report:
Explanation
Well, as i’ve found, there are actually two different issues:
- There is an offset between the point on the chart and the tick on the axis (as evidenced by the first chart).
- The labels repeat themselves because Highcharts falls on a smaller scales (days, not months), and your date format hides this from you.
Problem #1
Let me illustrate point 1 with a more obvious example:
You may not be seeing the same thing as me, but I get labels offset by -4 hours, which look suspiciously like a UTC vs localized dates issue. After trying a few solutions mostly involving Moment.js wizardry (amazing library, by the way), i stumbled across this. The solution is quite simple:
Problem #2
Now, on to issue #2. As before, let’s have an example to better illustrate the issue:
This one stumped me a lot longer than issue #1. I tried various possible solutions, including defining the axis as a ‘category’ axis (don’t go there, you may not come back), but I finally found the solution, again in the Highcharts documentation:
And voilà, the beautiful charts you’ve always wanted:
Conclusion
Highcharts is a very powerful library, but it can be hard sometimes to get it to do exactly what you want. However, as we’ve demonstrated here, there’s usually a way. Feel free to tweet me any question.