Assigning Colors to Specific Columns in Google Cha

2019-08-10 22:11发布

问题:

I would like to assign a specific color to each column in a Google Bar Chart. I was wondering what the best way is to go about doing this. I would like to include a color Hex code to each data point.

I have a jsfiddle below: http://jsfiddle.net/zYS27/

var option = {
  animation: {duration: 1000, easing: 'out',},
  hAxis: {textStyle:{
  fontName: 'Nunito',fontSize: '16' }},
  legend: { position: "none" },
  tooltip: {trigger: "none", textStyle:{
  fontName: 'Nunito',fontSize: '16' }, isHtml: true},
  bar: {groupWidth: "80%"},
  vAxis: {format:'0%', minValue:0, viewWindowMode:'maximized', textStyle:{
  fontName: 'Nunito',fontSize: '16' }, maxValue:1},
            };

    var formatter = new google.visualization.NumberFormat({
        fractionDigits: 3,
        pattern:'#,###%',
        });
  var data = new google.visualization.DataTable();    
  data.addColumn('string', 'N');
  data.addColumn('number', 'Value');
  data.addRow(['Orange', 0]);
  data.addRow(['Red', 0]);
  data.addRow(['Green', 0]);
  data.addRow(['Blue', 0]);
  data.addRow(['Purple', 0]);
  // Create and draw the visualization.
  var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
  chart.draw(data, option);
  data.setValue(0, 1, 0.1);
  data.setValue(1, 1, 0.3);
  data.setValue(2, 1, 0.4);    
  data.setValue(3, 1, 0.4);
  data.setValue(4, 1, 0.4);
  chart.draw(data, option);

  }

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);

回答1:

Use a "style" role column:

var data = new google.visualization.DataTable();    
data.addColumn('string', 'N');
data.addColumn('number', 'Value');
data.addColumn({type: 'string', role: 'style'});
data.addRow(['Orange', 0, 'color: #FF8000']);
data.addRow(['Red', 0, 'color: #FF0000']);
data.addRow(['Green', 0, 'color: #00FF00']);
data.addRow(['Blue', 0, 'color: #0000FF']);
data.addRow(['Purple', 0, 'color: #800080']);

fiddle: http://jsfiddle.net/asgallant/zYS27/1/



回答2:

You can also specify the option.colors

option.color = ['#0f0', '#00f'];