谷歌饼图百分比计算

时间:2016-01-14 06:11:00

标签: javascript jquery charts google-visualization google-pie-chart

我有一个以饼图形式显示数据的页面。我使用谷歌图表,这是代码:

 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Product', 'Sale In Percent'],
        ['product2', 5.5],
        ['product3', 7.5],
        ['product4', 1.5],
        ['product5', 8.5],
        ]);

        var options = {
          title: 'Product Sales'
        };

       var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
        chart.draw(data, options);
      }
    </script>
<div id="piechart2" style="width: 700px; height: 400px; position: relative;"></div>

这是一个有效的JS FIDDLE: https://jsfiddle.net/alex4uthis/j78vmq00/2/

这里我还有1个产品作为product1,它的值是77.由于这个值总是更高,我从图表中省略了。当我绘制图表时,我们可以看到product2百分比变为23.9%,product3百分比变为32.6等......但是我想得到饼图画,并且我已经在'百分比出售'中得到了它。列。(表示产品1用5.5等绘制...) 请帮助我。

1 个答案:

答案 0 :(得分:1)

您不能拥有总计小于100%的饼图,因此库假设您传递的值的总和将被视为100%。

由于您未通过77,因此您的值最多只能为23. 5.5/23 = 23.9%7.5/23 = 32.6%

如果您希望图表显示的标签显示您提供的百分比,则首先需要将pieSliceText选项设置为value,以使用'数量值'标记切片切片。' (https://developers.google.com/chart/interactive/docs/gallery/piechart?hl=en#configuration-options

接下来,如果你想用百分号显示标签,你只想在图表渲染之后手动添加它们:

[].slice.call(document.querySelectorAll('#piechart2 path + text'))
        .forEach(function(el) {
            el.textContent += '%';
        });

这是一个工作小提琴:https://jsfiddle.net/tq37y0p5/1/

相关问题