Sumedh
Sumedh

Reputation: 648

Highcharts - Display only year in x axis and stop auto formatting

This is how the chart looks like at the moment:

http://jsfiddle.net/YWLpr/2/

enter image description here

If you see the x axis, you can see Month as well as Year while I want to display just the year.

Surprisingly if you add one more data entry in the series

 [Date.UTC(2011,2,31), 11.30] 

The x axis auto formats itself and display only the year

e.g. - http://jsfiddle.net/YWLpr/3/

So if there are 7 data points I can see year in the x axis but if there are less than 7 data points I can see month and year which is not what I want. How can I stop this auto formatting and display only the year in x axis for less than 7 data points.

Upvotes: 4

Views: 12589

Answers (5)

Clay Teeter
Clay Teeter

Reputation: 1

xAxis: [{
    type: "datetime",
    tickInterval: 24 * 3600 * 1000 * 365 // mills in a year. 
}],

From Documentation:

Note that datetime axes are based on milliseconds, so for example an interval of one day is expressed as 24 * 3600 * 1000

Upvotes: 0

Kalel Wade
Kalel Wade

Reputation: 7792

I had to use a variation between @Pawel and @Sumedh. Basically, the key is the tick interval. If you don't set the interval, the graph will try to automatically zoom in and show months. The other thing is the datetimelabelformats work ok but I did notice one issue when there was only 1 point, it would still show the month, even if the month format is set to just show year. Below is the code that worked for me.

xAxis: {
    startOnTick: true,
    type: 'datetime',
    labels:
    {
        formatter: function () {
            return Highcharts.dateFormat("%Y", this.value);
        }
    },
    tickInterval: Date.UTC(2010, 0, 1) - Date.UTC(2009, 0, 1)
},

The formatter pretty much override all labels which is handy instead of having to deal with year, month etc. This will guarantee that the correct label is always shown.

Upvotes: 2

Sumedh
Sumedh

Reputation: 648

@Pawel's answer did not fully work for me. I could see repeated year values which is not what I want.

The following code worked for me.

xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: { 
            year: '%Y'
            },
            tickInterval: Date.UTC(2010, 0, 1) - Date.UTC(2009, 0, 1)

        }

Upvotes: 2

Paweł Fus
Paweł Fus

Reputation: 45079

You can always use label.formatter or label.format, see: http://jsfiddle.net/PwEnd/14/

Docs: http://api.highcharts.com/highcharts#xAxis.labels.format

Upvotes: 4

dgw
dgw

Reputation: 13646

If you resize the chart the zoomlevel will switch from year to month therefor you'll have to add a formatting option for month too:

        dateTimeLabelFormats: {
            month: '%Y',
            year: '%Y'
        }

Upvotes: 2

Related Questions