Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google table Chart : how do I change the row background color based on a column value

I am using google table chart to show some data as a table. Based on the status value on the row, I have to change the background color of the row. So I have to show multiple colors dynamically. I have checked the table chart documentation and also searched online. But could not find such a functionality provided. Please help.

like image 744
user2928913 Avatar asked Dec 19 '22 17:12

user2928913


1 Answers

Here are some options for you...

  1. Use the ColorFormat formatter

  2. Add your own html in the data by providing

    v: value
    f: formatted value
    and
    allowHtml: true configuration option

  3. Modify the table yourself on the 'ready' event

see following example which uses all three...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Department');
    data.addColumn('number', 'Revenues');
    data.addRows([
      ['Shoes', 10700],
      ['Sports', -15400],
      ['Toys', 12500],
      ['Electronics', -2100],
      ['Food', 22600],
      ['Art', 1100],
      [
        // add you own html
        {v: 'Web', f: '<div style="background-color: cyan;">Web</div>'},
        {v: 9999, f: '<div style="background-color: cyan;">9999</div>'}
      ]
    ]);

    var container = document.getElementById('table_div');
    var table = new google.visualization.Table(container);
    google.visualization.events.addListener(table, 'ready', function () {
      for (var i = 0; i < data.getNumberOfRows(); i++) {
        if (data.getValue(i, 1) === 1100) {
          // modify the table directly on 'ready'
          container.getElementsByTagName('TR')[i+1].style.backgroundColor = 'magenta';
        }
      }
    });

    // use formatter
    var formatter = new google.visualization.ColorFormat();
    formatter.addRange(-20000, 0, 'white', 'orange');
    formatter.addRange(20000, null, 'red', '#33ff33');
    formatter.format(data, 1); // Apply formatter to second column

    table.draw(data, {
      allowHtml: true
    });
  },
  packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></div>
like image 71
WhiteHat Avatar answered Apr 17 '23 14:04

WhiteHat