Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make rounded corner bars in google charts

I have following chart with square bars

enter image description here

I want it to make rounded corner bars with google charts like below pic

enter image description here

like image 467
Mihir Bhatt Avatar asked Aug 02 '16 10:08

Mihir Bhatt


1 Answers

there are no standard configuration options to change the shape of the column

but you can modify the svg directly when the chart's 'ready' event fires

however, the chart will revert back to the original shape, on any other event

so need to modify, anytime an event is fired
--> 'ready', 'select', 'onmouseover', 'onmouseout'

to change the border radius of a rect element, use the attributes rx and ry

to ensure we have the correct rect elements,
custom colors are provided to the chart
then the fill attribute is checked, to see if it exists in colors

rect elements with a fill attribute of 'none' are also included,
this will be the rect used to highlight the column 'onmouseover'

as well as rect elements with a stroke attribute of '#ffffff',
which are used to mark the selected column

one other note, the svg appears to change any colors to lower case,
so lower case colors are used in the array

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Month', '2015', '2016'],
      ['Jan', 10, 15],
      ['Feb', 12, 18],
      ['Mar', 14, 21],
      ['Apr', 16, 24]
    ]);

    var container = document.getElementById('chart_div');
    var chart = new google.visualization.ColumnChart(container);

    var colors = ['#cd6155', '#5499c7'];

    google.visualization.events.addListener(chart, 'ready', changeBorderRadius);
    google.visualization.events.addListener(chart, 'select', changeBorderRadius);
    google.visualization.events.addListener(chart, 'onmouseover', changeBorderRadius);
    google.visualization.events.addListener(chart, 'onmouseout', changeBorderRadius);

    function changeBorderRadius() {
      chartColumns = container.getElementsByTagName('rect');
      Array.prototype.forEach.call(chartColumns, function(column) {
        if ((colors.indexOf(column.getAttribute('fill')) > -1) ||
            (column.getAttribute('fill') === 'none') ||
            (column.getAttribute('stroke') === '#ffffff')) {
          column.setAttribute('rx', 20);
          column.setAttribute('ry', 20);
        }
      });
    }

    chart.draw(data, {
      colors: colors
    });
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
like image 85
WhiteHat Avatar answered Sep 28 '22 01:09

WhiteHat