3

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.

| |
9
0

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>

| |
0
0

When mixing HTML DOM with data object the rowIndex could be out of sync and edit the wrong row. In my case I used dashboard() and bind() with ChartWrapper() & ControlWrapper() to use StringFilter, so I avoided addListener() to change HTML DOM and rather modified data object before rendering:

for (var i = 0; i < data.getNumberOfRows(); i++) {
  if (data.getValue(i, 1) === 1100) {
    // change entire row
    data.setRowProperty(i, 'style', 'background-color:magenta;');
    // or change columns 0 & 1
    data.setProperty(i, 0, 'style', 'background-color:magenta;');
    data.setProperty(i, 1, 'style', 'background-color:magenta;');
  }
}
| |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.