I've used this script to show a chart bar with different colors in one series:
function drawAttendance() {
var data = new google.visualization.DataTable();
data.addColumn('string', '');
data.addColumn('number', '');
data.addColumn({ type: 'string', role: 'style' });
data.addRows(2);
data.setValue(0, 0, 'Value 1');
data.setValue(0, 1, 250);
data.setValue(0, 2, 'rgb(200, 20, 60)');
data.setValue(1, 0, 'Value 2');
data.setValue(1, 1, 100);
data.setValue(1, 2, 'rgb(20, 200, 60)');
var options = {
chartArea: {
left: 200,
height: '85%',
width: '100%',
},
bar: {groupWidth: "95%"},
legend: {position: 'none'},
hAxis: {
minValue: 0,
},
vAxis: {
},
height: '100%',
width: '100%',
};
chart.draw(data, options);
}
The problem: I need to show the annotation in the bar, but when I add the following code, the value is showed in the bar but the colours are lose (show all blue by default)
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
role: 'annotation',
sourceColumn: 1,
type: 'string'
}]);
chart.draw(view, options);
How to combine both formats (display value and different colours)?
you just need to make sure the style role is included in the view.
include column index 2, here...
view.setColumns([0, 1, 2, { // <-- include style role column index
calc: 'stringify',
role: 'annotation',
sourceColumn: 1,
type: 'string'
}]);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawAttendance);
function drawAttendance() {
var data = new google.visualization.DataTable();
data.addColumn('string', '');
data.addColumn('number', '');
data.addColumn({
type: 'string',
role: 'style'
});
data.addColumn({
type: 'string',
role: 'annotation'
});
data.addRows(2);
data.setValue(0, 0, 'Value 1');
data.setValue(0, 1, 250);
data.setValue(0, 2, 'rgb(200, 20, 60)');
data.setValue(1, 0, 'Value 2');
data.setValue(1, 1, 100);
data.setValue(1, 2, 'rgb(20, 200, 60)');
var options = {
chartArea: {
left: 200,
height: '85%',
width: '100%',
},
bar: {
groupWidth: "95%"
},
legend: {
position: 'none'
},
hAxis: {
minValue: 0,
},
vAxis: {},
height: '100%',
width: '100%',
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, {
calc: 'stringify',
role: 'annotation',
sourceColumn: 1,
type: 'string'
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>