如何在柱形图中使动态列颜色使用谷歌图表

时间:2017-05-17 10:51:56

标签: php charts google-visualization

我正在使用谷歌图表并显示柱形图。这工作正常。我的代码是

google.charts.load('current', {'packages':['columnchart']});
google.charts.setOnLoadCallback(drawChartTwo);
function drawChartTwo() {
var data = google.visualization.arrayToDataTable([
  ['Type', 'Total'],
  <?php
      foreach($val as $data){
        echo "['".$data['type']."', ".$data['total']."],";
      }
  ?>                    
]);

var options = {
  hAxis: {
      title: 'Type'
    },
    vAxis: {
      title: 'Total'
    },
  'width':830,
  'height':300,
   'title': 'Outage Analysis',
   'is3D': true,
   //set color base on $data['unit']
};


    var chart1 = new google.visualization.ColumnChart(document.getElementById('chart_bar'));

    chart1.draw(data, options);
}  

现在,在我的数据库中,我有另一列 $ data ['unit'] ,它有四个不同的类别,我想为不同的类别显示不同颜色的列。所以,我的问题是如何使用我的php列 $ data ['unit'] 在柱形图中的列上设置颜色?

1 个答案:

答案 0 :(得分:1)

使用'style' column role

您可以使用html颜色字符串填充列...

e.g。 - &GT; #f44336

var data = google.visualization.arrayToDataTable([
  ['Type', 'Total', {role: 'style'}],
  <?php
      foreach($val as $data){
        echo "['".$data['type']."', ".$data['total'].", '".$data['color']."'],";
      }
  ?>
]);

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

&#13;
&#13;
google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

function drawChart() {
  var data = new google.visualization.arrayToDataTable([
    ['Type', 'Total', {role: 'style'}],
    ['A', 10, '#f44336'],
    ['B', 14, '#e91e63'],
    ['C', 16, '#9c27b0'],
    ['D', 22, '#673ab7'],
    ['E', 28, '#3f51b5'],
    ['F', 14, '#2196f3']
  ]);

  var options = {
    height: 300,
    legend: {
      position: 'none'
    }
  };

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