Mar 1, 2013

Suppressing repeating x-axis date labels

For those of you familiar with Highcharts, you are probably aware that if you make an axis a datetime type that it will automatically and intelligently label your axis. There are some limitations with the standard formatting options though. Sometimes you want to tweak something a certain way and there doesn't seem to be a way to do it.

I came across a scenario where the users wanted the date labels to be just the year. I thought it would be easy, all I'd have to do is give it a dateformat of "%Y" to get a four digit year. The only problem with this was depending on how many ticks there were on the x-axis I would get the same label repeated multiple times. Not good! There is no option in highcharts to suppress repeating labels.

I came up with this solution that handles this problem perfectly!

I made use of a label formatter callback function like so:

xAxis: {
    type: 'datetime',
    labels: {
       formatter: function() {
var year = Highcharts.dateFormat('%Y', this.value);
if (prevYear == year) {
} else {
prevYear = year;
return year;

The formatter callback function will be called in a loop, once for each label. Javascript doesn't have a static variable so I just made use of a global variable "prevYear". I used the prevYear variable to suppress repeating labels. After making this change to my highcharts code, I just had to ensure that there was a global variable named prevYear available on the page that uses the highchart code and everything worked great!!

The following are screen shots of the results:

In this example there were enough labels that there was no repeating problems so this chart shows no change, it looks the same as it did before adding the suppressing logic.

In this example, the chart has been zoomed and there are fewer labels and the labels were repeating.

The label suppressing logic took care of this and here is the result:

If you look closely you can see ticks with no label. The two ticks after the 2005 label would have been 2005 repeated. Same with 2006 and 2007.

I hope this helps someone looking to suppress repeating axis labels.


No comments:

Post a Comment