如何在谷歌饼图中自动抵消最大切片?

时间:2016-02-26 20:11:12

标签: javascript google-visualization pie-chart

如何使用谷歌饼图找到并抵消最大片自动

google chart offset biggest slice

在这个例子中,它应该是印地语,有3亿人。

基本上我必须遍历数据并返回最高条目的索引。那么循环有更快的原因吗?

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>

1 个答案:

答案 0 :(得分:3)

利用API,您可以使用getSortedRows() method

data.getSortedRows([{column: 1, desc: true}])将返回排序的行ID数组。 index 0将是最大的一个。然后,将其应用到options变量

是一件简单的事情

&#13;
&#13;
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);
}
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart" style="width: 500px; height: 400px;"></div>
&#13;
&#13;
&#13;