Show horizontal gridlines between series on bar chart

Viewed 24

I have a bar chart that compares a budget with the money spent, for diferent categories.

The problem is, budget and progress can be zero, so the groups are hard to figure out, as can be seen in this JSFiddle.

It would be great to have a gridline that separates the groups, more obviously than with just empty space.

I can do it vertically, but it doesn't work horizontally.

    hAxis: {
      title: '$',
      minValue: 0,
      gridlines: {color: 'cyan'}
    },
    vAxis: {
      title: 'Food',
      gridlines: {color: 'red'}
    }

Can anyone help?

1 Answers

gridlines are only supported by a continuous axis (number, date, etc.)
they will not appear for a discrete axis (string)

in the data table, you can use object notation in order to use a continuous axis,
but still display a string value. ({v: 4, f: 'Pizza'})

['Food', 'Budgeted', 'Spent'],
[{v: 4, f: 'Pizza'}, 8175000, 7854695],
[{v: 3, f: 'Hamburger'}, 0, 2792000],
[{v: 2, f: 'Milkshake'}, 2695000, 0],
[{v: 1, f: 'Paella'}, 0, 0]

where v: is the value, and f: is the formatted value.

the value is used to control the order,
the formatted value will be displayed in the tooltip.

then, in order to display the labels on the axis,
we must use object notation in the ticks option.

  ticks: [
    {v: 0.5, f: ''},
    {v: 1, f: 'Paella'},
    {v: 1.5, f: ''},
    {v: 2, f: 'Milkshake'},
    {v: 2.5, f: ''},
    {v: 3, f: 'Hamburger'},
    {v: 3.5, f: ''},
    {v: 4, f: 'Pizza'},
    {v: 4.5, f: ''}
  ],

the ticks with the half value will add a line between.
but you won't be able to add grid lines only between.
because we must add a tick for the label itself.

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Food', 'Budgeted', 'Spent'],
    [{v: 4, f: 'Pizza'}, 8175000, 7854695],
    [{v: 3, f: 'Hamburger'}, 0, 2792000],
    [{v: 2, f: 'Milkshake'}, 2695000, 0],
    [{v: 1, f: 'Paella'}, 0, 0]
  ]);

  var options = {
    title: 'Food budgeted vs food spent',
    bar: {
      groupWidth: '75%',
    },
    chartArea: {width: '50%'},
    hAxis: {
      title: '$',
      minValue: 0,
      gridlines: {color: 'red'}
    },
    vAxis: {
      title: 'Food',
      ticks: [
        {v: 0.5, f: ''},
        {v: 1, f: 'Paella'},
        {v: 1.5, f: ''},
        {v: 2, f: 'Milkshake'},
        {v: 2.5, f: ''},
        {v: 3, f: 'Hamburger'},
        {v: 3.5, f: ''},
        {v: 4, f: 'Pizza'},
        {v: 4.5, f: ''}
      ],
      gridlines: {color: 'red'}
    }
  };

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
  chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related