the columns in a BarChart
or ColumnChart
will represented by <rect>
elements
however, there will be other <rect>
elements, such as the chart itself, gridlines, etc
so finding the correct <rect>
elements to modify is usually the hardest part
once the elements are found, use a MutationObserver
to override the style every time activity occurs
see following working snippet,
the colors of the columns are switched out for rgba
, which support transparency...
google.charts.load('current', {
callback: function () {
window.addEventListener('resize', drawChart, false);
drawChart();
},
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Y1', 'Y2'],
['2010', 10, 14],
['2020', 14, 22],
['2030', 16, 24],
['2040', 22, 30],
['2050', 28, 36]
]);
var seriesColors = ['#00ffff', '#ff00ff'];
var rgbaMap = {
'#00ffff': 'rgba(0,255,0,0.5)',
'#ff00ff': 'rgba(255,0,0,0.5)'
};
var options = {
colors: seriesColors,
};
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chartDiv);
// modify svg
var observer = new MutationObserver(function () {
Array.prototype.forEach.call(chartDiv.getElementsByTagName('rect'), function(rect) {
if (seriesColors.indexOf(rect.getAttribute('fill')) > -1) {
rect.setAttribute('fill', rgbaMap[rect.getAttribute('fill')]);
}
});
});
observer.observe(chartDiv, {
childList: true,
subtree: true
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
following is an example of a typical <rect>
element that represents a column
<rect x="283" y="113" width="27" height="48" stroke="none" stroke-width="0" fill="rgba(0,255,0,0.5)"></rect>
you'll notice there isn't an attribute for 'id'
you can access by index, but since there are more <rect>
elements than columns, you'll need to use something like width
or fill
in addition
to access by index...
chartDiv.getElementsByTagName('rect')[0]
chartDiv.getElementsByTagName('rect')[1]
setting a specific color is an easy way to identify, similar to above snippet...