Google Bar Chart cannot Change Individual Bar Color
each color in the colors
option is applied to each series / y-axis column in the data table.
if there is only one y-axis column, only one color will be applied.
Otherwise, a Style Column Role is the easiest way to color an individual bar.
However, it does not work on Material Charts.
For options, see example charts...
Chart 1 = Material Chart
Chart 2 = Core Chart
Both built the same way with various style settings
Works on Core, not on Material
If you are fine with each bar being the same color...
Chart 3 = Material Chart
Usescolors
configuration option to change the color to red
Only one series exists, so accepts only one color
If you must have Material Chart with separate colors for each bar...
Chart 4 = Material Chart
Each value is added as a column, instead of a row, creating multiple series
Usescolors
configuration option to change color for each bar
series
option can also be used here
However, much harder to work with, noticeSpacer
column and lack ofhAxis
labels...
google.charts.load('current', { callback: init, packages: ['bar', 'corechart']});
function init() { var jsonCoachCount = JSON.parse('[{"Service_Count":"4","Name":"Other"}, {"Service_Count":"4","Name":"Campus Network"},{"Service_Count":"3","Name":"Learn@UW"},{"Service_Count":"2","Name":"Customer Service"},{"Service_Count":"1","Name":"Blackboard Collaborate"},{"Service_Count":"1","Name":"Office 365"},{"Service_Count":"1","Name":"Multiple"},{"Service_Count":"1","Name":"Office-ionado"},{"Service_Count":"1","Name":"Case Notes"},{"Service_Count":"1","Name":"ResNet"}]');
var options = { backgroundColor: { fill: '#E8E4D8' }, legend: { position: 'none' }, titleTextStyle:{ bold: 'true' }, chart: { title: 'Coaches by Service', subtitle: 'Coaches by Services: From 2016-09-10 until Today' }, bar: { groupWidth: '60%' }, hAxis: { textStyle: { fontSize: 11 } } };
drawChart(); drawSeriesChart();
function drawChart() { var servicesData = new google.visualization.DataTable();
servicesData.addColumn('string', 'Service'); servicesData.addColumn('number', 'Number of Coaches'); servicesData.addColumn({type:'string', role:'style'});
for (i = 0; i < jsonCoachCount.length; i++) { var tempArray =[]; var tempColor; switch (i) { case 0: tempColor = 'color:Red'; break;
case 1: tempColor = 'orange'; break;
case 2: tempColor = 'fill-color: gold;'; break;
case 3: tempColor = 'bar {color: green;}'; break;
case 4: tempColor = 'bar {fill-color: blue;}'; break;
default: tempColor = 'bar {fill-color: cyan; stroke-color: black; stroke-width: 4;}'; } tempArray.push( String (jsonCoachCount[i]['Name']), parseInt(jsonCoachCount[i]['Service_Count']), tempColor ); servicesData.addRow(tempArray); }
var chart = new google.charts.Bar(document.getElementById('servicesChart1')); chart.draw(servicesData, google.charts.Bar.convertOptions(options));
var chart = new google.visualization.ColumnChart(document.getElementById('servicesChart2')); chart.draw(servicesData, options);
// only one series exists -- only one color will work options.colors = ['red']; var chart = new google.charts.Bar(document.getElementById('servicesChart3')); chart.draw(servicesData, google.charts.Bar.convertOptions(options)); }
function drawSeriesChart() { var servicesData = new google.visualization.DataTable();
servicesData.addColumn('string', 'Service'); for (i = 0; i < jsonCoachCount.length; i++) { servicesData.addColumn('number', String (jsonCoachCount[i]['Name'])); servicesData.addColumn('number', 'Spacer'); }
var tempArray = []; tempArray.push('Number of Coaches'); for (i = 0; i < jsonCoachCount.length; i++) { tempArray.push(parseInt(jsonCoachCount[i]['Service_Count'])); tempArray.push(null); } servicesData.addRow(tempArray);
options.colors = [ 'deeppink', 'red', 'orange', 'gold', 'green', 'blue', 'indigo', 'purple', 'violet', 'pink' ];
var chart = new google.charts.Bar(document.getElementById('servicesChart4')); chart.draw(servicesData, google.charts.Bar.convertOptions(options)); }}
div { padding: 2px 0px 2px 0px; font-weight: bold;}
.code { background-color: lightgray; font-family: Courier New;}
<script src="https://www.gstatic.com/charts/loader.js"></script><div>1. Material Chart</div><div id="servicesChart1"></div><div>2. Core Chart</div><div id="servicesChart2"></div><div>3. Material Chart with <span class="code">colors: ['red']</span></div><div id="servicesChart3"></div><div>4. Multi-Series Material Chart</div><div id="servicesChart4"></div>
Google Charts - Change individual bar color
Here is a code sample that changes the color. Note that the
"colors" option accepts an array of strings.
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}},
colors: ['red','green'],
is3D:true
};
i am working on google bar charts, i am stuck with adding colours to individual bars
the column headings and values posted in the above comments seem to work fine here...
the only changes made...
- add
type
property to style and annotation roles. - added different colors for style role.
see following working snippet...
var a = [['Work', 8, "#E53935", 8], ['Eat', 2, "#1E88E5", 2], ['TV', 4, "#43A047", 4]];
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] > b[1]) ? -1 : 1;
}
}
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day', {role: 'style', type: 'string'}, {role: 'annotation', type: 'number'}],a[0],a[1],a[2]
]);
var options = {
title: 'the title',
width: 550,
height: 400,
legend: 'none'
};
var chart = new google.visualization.ColumnChart(document.getElementById('piechart'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>
Google Chart Color individual Bars
The reason that this is not working is because the google.charts.Bar(...)
object that you are creating is what Google calls a Material Chart. This is a completely redesigned implementation of the Google Visualization API, distinct from what they call the "Classic" chart packages and this still currently in beta. There are a number of related questions on here (see below) and it appears that column roles (as you have used here to designate 'color'
) are not yet supported for Material Charts.
If you want to use customised styles for each data point, you have to use the older (but much better supported) Google Visualization "Classic" corechart package as follows. The initial design of the chart is a bit different, but the more extensive customization options should mean that you can get it to look how you want!
google.charts.load('current', { packages: ['corechart' /*, 'bar'*/ ] /* Don't need to load the bar package */});google.charts.setOnLoadCallback(drawDualX);
function drawDualX() { var data = google.visualization.arrayToDataTable([ ['Date', 'Elevation', { role: 'style' }], ['2016-08-06T08:09:47Z', 1977.4, 'color: yellow'], ['2016-08-06T08:13:29Z', 1981, 'color: green'], ['2016-08-06T08:14:08Z', 1986.9, 'color: yellow'], ['2016-08-06T08:14:22Z', 1988.9, 'color: green'], ['2016-08-06T08:14:25Z', 1989.2, 'color: green'], ['2016-08-06T08:14:29Z', 1989.7, 'color: yellow'], ['2016-08-06T08:14:32Z', 1990.1, 'color: green'], ]); var options = { chart: { title: 'Elevation Chart', }, //bars: 'vertical' /* This option isn't required for "Classic" column chart */ };
/* Create a "Classic" Google Visualization Column Chart */ var material = new google.visualization.ColumnChart(document.getElementById('chart_div')); material.draw(data, options);}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><div id="chart_div"></div>
How to set a specific color for a specific bar in Google charts?
So, it turned out - as Mr. WhiteHat cleared out - that the Material Charts do not support the majority of the useful customization options just yet... Which are all listed here:
https://github.com/google/google-visualization-issues/issues/2143
Hence, I'm obliged - as Mr. عارف بن الأزرق suggested - to use the Core Charts ALONG WITH the "material" theme provided in the following question's answer:
Google Chart (Material) - Type Bar - Data in arrayToDataTable with role style KO?
Google Charts bar chart: How to manually change the colour of every bar? (single series)
There are different ways to do this but you can use the style role.
Source:
https://developers.google.com/chart/interactive/docs/gallery/columnchart#Colors
google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Product', 'Score', { role: 'style' }], ['NemakiWare', 288, 'green'], ['Nuxeo', 240, 'blue'], ['FileNet', 220, 'pink'], ['SharePoint', 98, 'red'] ]);
var options = { legend: 'none', hAxis: { textPosition: 'none', minValue: 0, gridlines: { color: 'transparent' } } };
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));chart.clearChart(); chart.draw(data, options); }
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script> <div id="chart_div" style="width: 900px; height: 500px;"></div>
Google Diff Bar Chart - Change Bar Color
You can set that in the diff object, e.g.,
var options = { ...
diff: {
oldData: { opacity: 1, color: '#e6693e' },
newData: { opacity: 1}
}...
}
Color the bars of Barchart differently in Google Charts
you can use a style column role...
google.charts.load('current', { packages:['corechart']}).then(function () { var chart = new google.visualization.BarChart(document.getElementById('chart-bar')); chart.draw(new google.visualization.DataTable({ "cols": [ {"label":"Topping","pattern":"","type":"string"}, {"label":"Slices","pattern":"","type":"number"}, {"role":"style","type":"string"} ], "rows": [ {"c":[{"v":"Mushrooms"},{"v":3},{"v":'green'}]}, {"c":[{"v":"Onions"},{"v":1},{"v":'red'}]}, {"c":[{"v":"Olives"},{"v":1},{"v":'blue'}]}, {"c":[{"v":"Zucchini"},{"v":1},{"v":'purple'}]}, {"c":[{"v":"Pepperoni"},{"v":2},{"v":'orange'}]} ] }));});
<script src="https://www.gstatic.com/charts/loader.js"></script><div id="chart-bar"></div>
Related Topics
Getting a Jquery Selector for an Element
$Http.Get(...).Success Is Not a Function
JavaScript Custom Event Listener
Where Should Ajax Request Be Made in Flux App
Array Like Objects in JavaScript
Change Route Params Without Reloading in Angular 2
Case Insensitive Jquery Attribute Selector
Firebase Callable Function + Cors
Example of a Circular Reference in JavaScript
Lodash Remove Duplicates from Array
Typescript: Deep Keyof of a Nested Object, with Related Type
How to Check If Element Has Any Children in JavaScript
JavaScript Es6 Cross-Browser Detection
JavaScript Reload the Page with Hash Value