首页 > 解决方案 > 条形图背景操作

问题描述

我正在尝试使用“斑马”背景实现条形图,而不是使用谷歌图表使用默认网格线。

有没有办法做到这一点?到目前为止无法弄清楚如何。

这就是我想要实现的目标:

这就是我到目前为止所得到的: 在此处输入图像描述

标签: chartsgoogle-visualization

解决方案


没有可用于更改网格线宽度的配置选项。

但是,您可以手动更改图表的'ready'事件。

请参阅以下工作片段...

在这里,次要网格线被移动以与轴标签对齐。
并且宽度增加到下一个轴标签的位置。

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>


推荐阅读