0

enter image description here

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

// Draw the chart and set the chart values
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', 8],
    ['Eat', 2],
    ['TV', 4],
    ['Gym', 2],
    ['Sleep', 8],
    ['walk', 2],
    ['games', 2],
    ['chess', 2],
    ['drink', 4],
    ['dance', 6]
  ]);

  // Optional; add a title and set the width and height of the chart
  var options = {
    'title': 'My Average Day',
    'width': 550,
    'height': 400
  };

  // Display the chart inside the <div> element with id="piechart"
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
}
<div id="piechart"></div>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  1. i am showing 10 different works in google chart
  2. some of them are low percentage and some of them are high
  3. can anybody help me with how to show only top 5 high percentage values in google pie chart
abhi
  • 93
  • 7

1 Answers1

0

My solution would be to save the values to an array, sort the array, then go through the first five.

Sort:

var a = [['Work', 8],['Eat', 2],['TV', 4],['Gym', 2],['Sleep', 8],['walk', 2],['games', 2],['chess', 2],['drink', 4],['dance', 6]];
a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] > b[1]) ? -1 : 1;
    }
}

for the graph:

var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],a[0],a[1],a[2],a[3],a[4]
]);

all together:

var a = [['Work', 8], ['Eat', 2], ['TV', 4], ['Gym', 2], ['Sleep', 8], ['walk', 2], ['games', 2], ['chess', 2], ['drink', 4], ['dance', 6]];
a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] > b[1]) ? -1 : 1;
    }
}



// Draw the chart and set the chart values
function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],a[0],a[1],a[2],a[3],a[4]
        
    ]);
    // Optional; add a title and set the width and height of the chart
    var options = { 'title': 'the title', 'width': 550, 'height': 400 };
    // Display the chart inside the <div> element with id="piechart"
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}

Check out this post for more information on the sort:

https://stackoverflow.com/a/16097058/10958914

Captain
  • 420
  • 5
  • 14