1
votes

I have Pie and Column charts from the same source data.

enter image description here

I want colors in bar chart to have the corrsponding colors like in Pie chart. These are default Google Charts colors (in order). So first column should be blue, second red, third yellow and fourth green. How to achieve this?

1

1 Answers

0
votes

in a column chart, values in the same series are the same color by default

series are defined by columns, to have different colors by default,
place each value in a separate column

however, this presents a problem

if you structure the data as follows, then you lose the x-axis labels
you only have one label for all columns

var data = google.visualization.arrayToDataTable([
  ['x', 'y0', 'y1', 'y2', 'y3'],
  ['Razina0', 898, 37319, 8980, 35400]
]);

if you try the next approach, then the columns will not be spaced properly
there will be gaps for the null values

var data = google.visualization.arrayToDataTable([
  ['x', 'y0', 'y1', 'y2', 'y3'],
  ['Razina0', 898, null, null, null],
  ['Razina1', null, 37319, null, null],
  ['Razina2', null, null, 8980, null],
  ['Razina3', null, null, null, 35400],
]);

the best option is to use a style column
this will allow you to keep the current data structure
and provide different colors for each column

the only drawback is you have to provide the color
so you lose the default colors


as such, recommend drawing the pie chart first
then use the colors assigned to each slice
when the pie chart's 'ready' event fires

see following working snippet...

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    ['Razina0', 898],
    ['Razina1', 37319],
    ['Razina2', 8980],
    ['Razina3', 35400]
  ]);

  var chartPie = new google.visualization.PieChart(document.getElementById('chart_pie'));
  var chartColumn = new google.visualization.ColumnChart(document.getElementById('chart_column'));

  google.visualization.events.addListener(chartPie, 'ready', function () {
    var colIndex = data.addColumn({type: 'string', role: 'style'});
    $.each($('#chart_pie path'), function (rowIndex) {
      data.setValue(rowIndex, colIndex, $(this).attr('fill'));
    });

    chartColumn.draw(data, {
      legend: {
        position: 'none'
      }
    });
  });

  chartPie.draw(data, {
    height: 240
  });
}
div {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_pie"></div>
<div id="chart_column"></div>