Google Line Chart: Change color when line down

混江龙づ霸主 提交于 2019-12-01 08:12:36

use a DataView and setColumns to provide a function that determines line direction
and returns the appropriate line color

see following working snippet...

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

function drawLineColors() {
  var data = new google.visualization.DataTable();
  data.addColumn('number', 'X');
  data.addColumn('number', 'Y');
  data.addRows([
    [0, 2000],
    [3, 1700],
    [6, 1400],
    [9, 2500],
    [12, 3000],
    [15, 4700],
    [18, 2200],
    [21, 1500],
    [24, 1200],
    [27, 1800],
    [30, 2600],
    [33, 2800],
    [36, 3000],
    [39, 2300],
    [42, 2000],
    [45, 4000]
  ]);

  var options = {
    curveType: 'function',
    height: 200,
    legend: {
      position: 'top'
    }
  };

  var dataView = new google.visualization.DataView(data);
  dataView.setColumns([
    // reference existing columns by index
    0, 1,
    // add function for line color
    {
      calc: function(data, row) {
        var colorDown = '#0000FF';
        var colorUp = '#FF0000';

        if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
          return colorDown;
        } else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
          return colorDown;
        }
        return colorUp;
      },
      type: 'string',
      role: 'style'
    }
  ]);

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(dataView, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!