Google Chart Add Color Specific

淺唱寂寞╮ 提交于 2021-02-02 03:46:27

问题


How are you?

How do I force the color? I do not want them to be random. I read the documentation, but something is wrong. I can not tell. They help me? Thank you very much!

For Example: I want the Womens records in Black and the mens in Green.

Regarts!

google.charts.load('current', {'packages':['corechart']});  
 		google.charts.setOnLoadCallback(drawChart);  
 		function drawChart()  
 		{  
 			var data = google.visualization.arrayToDataTable([  
 				['status', 'number',{ role: 'style' },{ role: 'annotation' } ],  
				["Men", 5, '#b87333','M'],
 				["Girl", 7, '#0000FF','G'],
        ]);  
 			var options = {  
 				title: 'Sex',  
 				is3D:true,  
 				pieHole: 0.4,
 				//colors: ['#5cb85c','#f0ad4e']
 				
 			};  
 			var chart = new google.visualization.PieChart(document.getElementById('piechart'));  
 			chart.draw(data, options);  
 		}  
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>

回答1:


the only role supported by PieChart is 'tooltip'

both 'style' and 'annotation' are not supported

you can either use the colors configuration option,

colors: ['#5cb85c','#000000']

or the slices option...

slices: [{color: '#5cb85c'}, {color: '#000000'}]

in both options above, the first color in the array will be applied to the first row in the data table,
the second color, the second row, etc...

if you're not sure in which order the data will be,
you can use an object to map the values to a specific color

here, we build the array of colors, by matching the values in the data table,
to the key in the color map object...

var colors = [];
var colorMap = {
  'Men': '#5cb85c',
  'Girl': '#000000'
}
for (var i = 0; i < data.getNumberOfRows(); i++) {
  colors.push(colorMap[data.getValue(i, 0)]);
}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['status', 'number'],
    ['Men', 5],
    ['Girl', 7]
  ]);

  var colors = [];
  var colorMap = {
    'Men': '#5cb85c',
    'Girl': '#000000'
  }
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    colors.push(colorMap[data.getValue(i, 0)]);
  }

  var options = {
    title: 'Sex',
    is3D: true,
    colors: colors
  };
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
});
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>  
<script type="text/javascript"> </script>
<!--Div that will hold the pie chart-->
<div id="piechart"></div>


来源:https://stackoverflow.com/questions/50079481/google-chart-add-color-specific

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!