Google图表 - 更改条形图颜色

时间:2016-12-26 16:10:58

标签: charts google-visualization

我有一个图表如下图所示:



      google.charts.load('current', {'packages':['corechart']});
           
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['C', 0.03, 0.03, 0.06, 0.06, 0.02, 0.02, 0.035, 0.035],
            ['Mn', 1.1, 1.1, 1.4, 1.4, 1, 1, 1.3, 1.3],
            ['Si', 0.3, 0.3, 0.7, 0.7, 0.35, 0.35, 0.7, 0.7]
        ], true);

        var options = {
          legend: 'none',
          bar: { groupWidth: '100%' }, // Remove space between bars.
          //colors: ['#fcb441', 'red', 'black']
          series: {
            0:{color:'red'},
            1:{color:'black'},
          }
        };

        var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }    

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
       <div id="chart_div" style="width: 900px; height: 500px;"></div>
&#13;
&#13;
&#13;

我需要根据值更改每个元素的第二个条的颜色。

例如:To&#34; C&#34;元素,将黄色设置为颜色是必要的,但是对于&#34; Mn&#34;元素,将绿色设置为条形颜色是必要的......

1 个答案:

答案 0 :(得分:1)

series...color选项根据列分配颜色 所以它会为所有行分配相同的颜色,具体取决于列(系列)

为每个行/元素指定特定颜色,
使用'style' column role

请参阅以下工作代码段...

google.charts.load('current', {
  callback: function () {
    drawChart();
    window.addEventListener('resize', drawChart, false);
  },
  packages:['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Label', 'Low 0', 'Open 0', 'Close 0', 'High 0', {role: 'style'}, 'Low 1', 'Open 1', 'Close 1', 'High 1', {role: 'style'}],
    ['C', 0.03, 0.03, 0.06, 0.06, 'black', 0.02, 0.02, 0.035, 0.035, 'yellow'],
    ['Mn', 1.1, 1.1, 1.4, 1.4, 'black', 1, 1, 1.3, 1.3, 'lime'],
    ['Si', 0.3, 0.3, 0.7, 0.7, 'black', 0.35, 0.35, 0.7, 0.7, 'magenta']
  ]);

  var options = {
    legend: 'none',
    bar: {
      groupWidth: '100%'
    }
  };

  var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>