2

I have a page that displays data in a form of a Pie Chart. I use Google Charts and here is the code:

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

And here's a working JS FIDDLE: https://jsfiddle.net/alex4uthis/j78vmq00/2/

Here I have 1 more product as product1 and its value is 77. Since this value is always higher I omitted from the chart. When I draw the chart we can see product2 percent become 23.9%, product3 percent become 32.6 etc.... But I want to get the pie chart draw with what I have given in 'Sale In Percent' column.(Means product1 draw with 5.5 etc...) Please help me in this.

Alex
  • 790
  • 1
  • 7
  • 22
  • What goal are you trying to achieve? Do you want it to draw a partial circle? Or draw it as it is currently but with the labels reading your supplied number instead of the calculated percent? – Ted A. Jan 14 '16 at 06:41
  • I want a full circle with supplied percentage values. – Alex Jan 14 '16 at 06:42
  • I understand. That is a sort of odd chart since the labeled percentages won't match the visual representation... but my answer has been updated to do that if it is what you want to do. – Ted A. Jan 14 '16 at 07:19

1 Answers1

1

You can't have a pie chart that totals less than 100%, so the library is assuming the sum of the values you pass it is to be considered 100%.

Since you aren't passing the 77, your values only add up to 23. 5.5/23 = 23.9% and 7.5/23 = 32.6%

If you want to have the chart display with the labels reading your provided percentages, the first thing you need to do is set the pieSliceText option to value to label the slice with 'The quantitative value of the slice.' (https://developers.google.com/chart/interactive/docs/gallery/piechart?hl=en#configuration-options)

Next, if you want to show the label with a percent sign you will just want to go manually add them after the chart renders like so:

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

Here is a working fiddle: https://jsfiddle.net/tq37y0p5/1/

Ted A.
  • 2,264
  • 17
  • 22