1
votes

i'm trying to implement a bar chart with "zebra" background instead of having the default grid lines using google charts.

is there a way to achieve so? so far couldn't figure out how.

here's what i'm trying to achieve:

and here's what i've got so far: enter image description here

1

1 Answers

1
votes

there are no configuration options you can use to change the width of the gridlines.

however, you can manually change, on the chart's 'ready' event.

see following working snippet...

here, the minor gridlines are moved to align with the axis labels.
and the width is increased to the position of the next axis label.

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['X', 'Y'],
    ['school_score', 80],
    ['salary_score', 72],
    ['benefits_score', 50],
    ['work_environment', 42],
    ['security_score', 35]
  ]);

  var container = document.getElementById('chart');
  var chart = new google.visualization.BarChart(container);

  google.visualization.events.addListener(chart, 'ready', function () {
    // find gridlines
    var gridlines = container.getElementsByTagName('rect');
    var minor = [];
    Array.prototype.forEach.call(gridlines, function(gridline) {
      if ((gridline.getAttribute('width') === '1') && (gridline.getAttribute('fill') === '#ebebeb')) {
        minor.push(gridline);
      }
    });

    // increase width of every other minor gridline, make the rest transparent
    var index = 0;
    var labelBounds;
    var labelBoundsNext;
    var chartLayout = chart.getChartLayoutInterface();
    while ((labelBounds !== null) && (index < minor.length)) {
      if (index % 2 === 0) {
        // use axis label bounds to determine width
        labelBounds = chartLayout.getBoundingBox('hAxis#0#label#' + index);
        labelBoundsNext = chartLayout.getBoundingBox('hAxis#0#label#' + (index + 1));
        minor[index].setAttribute('x', labelBounds.left);
        minor[index].setAttribute('width', (labelBoundsNext.left - labelBounds.left + labelBounds.width));
      } else {
        minor[index].setAttribute('fill', 'transparent');
      }
      index++;
    }
  });

  chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>