Is it possible to have different legend background colors for different data rows in Google bar chart, without breaking the chart?

喜你入骨 提交于 2019-11-29 16:30:55
WhiteHat

Not sure what you mean by breaking the chart, but...

You can modify the chart svg, once the 'ready' event fires.

This example changes the color of the legend text to match the bar color.

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var colors = ['#8bba30', '#ffcc33'];
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Mac');
  data.addColumn('number', 'Score');
  data.addColumn({ type: 'string', role: 'style' });
  data.addRows([
     ['Mac model 12', 200, 'color: ' + colors[0] + '; opacity: 0.75;'],
     ['Another Mac Model', 110, 'color: ' + colors[1] + '; opacity: 0.75;'],
  ]);
  var options = {
      title: '',
      width: 500,
      height: data.getNumberOfRows() * 40 + 100,
      hAxis: {
          minValue: 0,
          maxValue: 255,
          ticks: [0, 75, 150, 255],
          textPosition: 'out',
          side: 'top'
      },
      series: {
          0: { axis: 'Mac' },
          1: { axis: 'Score' }
      },
      chartArea: {
          top: 0,
          bottom: 50,
          right: 50,
          left: 150
      },
      legend: { position: 'none' },
      fontSize: 12,
      bar: {groupWidth: '75%'},
  };

  var chartContainer = document.getElementById('apple_div');
  var chart = new google.visualization.BarChart(chartContainer);
  google.visualization.events.addListener(chart, 'ready', function () {
    var labels = chartContainer.getElementsByTagName('text');
    var colorIndex = 0;
    for (var i = 0; i < labels.length; i++) {
      if (labels[i].getAttribute('text-anchor') === 'end') {
        labels[i].setAttribute('fill', colors[colorIndex]);
        colorIndex++;
      }
    }
  });
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="apple_div"></div>

As for background color, SVG elements do not have background
so you would have to draw your own rect for that...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!