Search code examples
javascriptgoogle-visualizationpie-chart

How to offset the biggest slice automatically in google pie chart?


How can I find and offset the biggest slice automatically using google pie chart?

google chart offset the biggest slice

In this example it should be the language Hindi with 300 millions speakers.

Basically, I have to loop through the data and return the index of the highest entry. Is there a faster way than a loop?

google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Language', 'Speakers (in millions)'],
    ['Assamese', 13], ['Bengali', 83], ['Bodo', 1.4],
    ['Dogri', 2.3], ['Gujarati', 46], ['Hindi', 300],
    ['Kannada', 38], ['Kashmiri', 5.5], ['Konkani', 5],
    ['Maithili', 20], ['Malayalam', 33], ['Manipuri', 1.5],
    ['Marathi', 72], ['Nepali', 2.9], ['Oriya', 33],
    ['Punjabi', 29], ['Sanskrit', 0.01], ['Santhali', 6.5],
    ['Sindhi', 2.5], ['Tamil', 61], ['Telugu', 74], ['Urdu', 52]
  ]);

  var options = {
    title: 'Indian Language Use',
    legend: 'none',
    pieSliceText: 'label',
    slices: {  5: {offset: 0.1}
            }
  };

  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart" style="width: 500px; height: 400px;"></div>


Solution

  • Utilizing the API, you can use the getSortedRows() method.

    data.getSortedRows([{column: 1, desc: true}]) will return the sorted array of row IDs. index 0 will be the largest one. Then it's a simple matter of applying that to your options variable:

    google.charts.load("current", {packages:["corechart"]});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Language', 'Speakers (in millions)'],
        ['Assamese', 13], ['Bengali', 83], ['Bodo', 1.4],
        ['Dogri', 2.3], ['Gujarati', 46], ['Hindi', 300],
        ['Kannada', 38], ['Kashmiri', 5.5], ['Konkani', 5],
        ['Maithili', 20], ['Malayalam', 33], ['Manipuri', 1.5],
        ['Marathi', 72], ['Nepali', 2.9], ['Oriya', 33],
        ['Punjabi', 29], ['Sanskrit', 0.01], ['Santhali', 6.5],
        ['Sindhi', 2.5], ['Tamil', 61], ['Telugu', 74], ['Urdu', 52]
      ]);
    
      var options = {
        title: 'Indian Language Use',
        legend: 'none',
        pieSliceText: 'label',
        slices: {}
      };
      options.slices[data.getSortedRows([{column: 1, desc: true}])[0]] = {offset: 0.1};
    
      var chart = new google.visualization.PieChart(document.getElementById('piechart'));
      chart.draw(data, options);
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="piechart" style="width: 500px; height: 400px;"></div>