0

在此处输入图像描述

// 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. 我在谷歌图表中展示了 10 件不同的作品
  2. 其中一些比例低,一些比例高
  3. 任何人都可以帮助我如何在谷歌饼图中只显示前 5 个高百分比值
4

1 回答 1

0

我的解决方案是将值保存到数组中,对数组进行排序,然后遍历前五个。

种类:

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;
    }
}

对于图表:

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

全部一起:

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);
}

查看这篇文章以获取有关排序的更多信息:

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

于 2020-08-03T14:18:59.883 回答