Renu Thakur
Renu Thakur

Reputation: 551

Show month in google chart hAxis

We are trying to show horizontal and vertical lines in google chart. For this we need to use hAxis and vAxis attribute.

But hAxis.format does not have any format for month, So how we can show vertical line?

  var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', ],
    ['Jan', 1000],
    ['Feb', 1170],
    ['Mar', 660],
    ['Apr', 1030]
]);

var options = {
    title: '',
    hAxis: {
        title: 'Year',
        minValue: 0,
        titleTextStyle: {
            color: '#333'
        },
        gridlines: {
            color: '#f3f3f3',
            count: 5
        },
         format: 'MMM'
    },
    vAxis: {
        minValue: 0,
        gridlines: {
            color: '#f3f3f3',
            count: 5
        }
    }
};

JsFiddle

And here is year jsFiddle which is showing both lines( horizontal and vertical )

Working Fiddle

Upvotes: 3

Views: 5920

Answers (1)

Niki van Stein
Niki van Stein

Reputation: 10724

Yes there is, but it is not so straight forward.
First thing you should know is that there is no option to create vertical lines for a major column of type string. So we need to use a column type of number for example and fix the labels later.

To do that we define the datatable like this:

var data = new google.visualization.DataTable();
        data.addColumn('number', 'Month');
        data.addColumn('number', 'Sales');
        data.addRows([
        [{v: 0, f:'Jan'}, 1000],
        [{v: 1, f:'Feb'}, 1170],
        [{v: 2, f:'Mar'}, 660],
        [{v: 3, f:'Apr'}, 1030]
    ]);

Where we set number values but also string labels for the Month axis.
With just this and the format attribute removed, we would get vertical lines but numbers instead of the strings for the x axis labels, which is not what we want.
To fix this we can set hAxis ticks to force the correct labels in the plot.

var options = {
        title: '',
        hAxis: {
            title: 'Month',
            titleTextStyle: {
                color: '#333'
            },
            baseline: 0,
            gridlines: {
                color: '#f3f3f3',
              count: 4
            },
           ticks: [{v: 0, f:'Jan'},{v: 1, f:'Feb'},{v: 2, f:'Mar'},{v: 3, f:'Apr'}], // <------- This does the trick
        },
        vAxis: {
            minValue: 0,
            gridlines: {
                color: '#f3f3f3',
                count: 5
            }
        }
    };

Hereby the complete working fiddle: http://jsfiddle.net/j29Pt/417/

Upvotes: 6

Related Questions