Google Line Chart: Change color when line down

前端 未结 1 1880
慢半拍i
慢半拍i 2021-01-14 00:57

https://developers.google.com/chart/interactive/docs/gallery/linechart

Hello, guys, I would like to know that is there a way to change the color of the line when it

相关标签:
1条回答
  • 2021-01-14 01:06

    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>

    0 讨论(0)
提交回复
热议问题