Show label and percentage in Google pie chart
Asked Answered
W

2

6

I would like to show label and percentage in Google pie chart. Is there any way to do it? In the docs, I found that it is possible to modify text with pieSliceText option. Possible values are:

label - show name of data (e. g. Apples)

value - show absolute value (e. g. 7)

percentage - show percentage value (e. g. 50%)

value-and-percentage - show both value and percentage (e. g. 7 (50%))

But is there something like label-and-percentage to show something like that Apples (50%)?

Wag answered 10/12, 2018 at 22:11 Comment(0)
P
6

the only config option that will show both the label & percentage is for the legend...

legend: {
  position: 'labeled'
},

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Tasks', 'Completed'],
    ['Morning', 28],
    ['Afternoon', 43],
    ['Evening', 80],
    ['Night', 161]
   ]);

  var options = {
    width: 900,
    height: 400,
    title: 'Tasks Completed',
    pieHole: 0.5,
    colors: ['#008000', '#ffbf00', '#FF0000','#4E6282'],
    pieSliceText: 'value',
    sliceVisibilityThreshold :0,
    fontSize: 17,
    legend: {
      position: 'labeled'
    },
  };

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Phipps answered 11/12, 2018 at 13:3 Comment(2)
Hi, Is it possible that, this line starts from outer side of pie slice, right now as you can see its cutting the number.Wineshop
no config options available, but you can modify the line manually, on the chart's 'ready' event...Phipps
F
3

You can show either label or percentage on pie charts. Look at the pieSliceText options here.

But if this is your requirement and you HAVE to show label and percentage both on pie chart that you can try this: set, pieSliceText: 'value' in options. And then pass formatted value in data of chart by calculating the percentage of every slice data and passing the label + percentage as formatted value:

data.addRows([
  ['Label', {v:value, f:'formatted value'}],
]);
  • here v: is the value of chart

  • and f: is formatted value of chart which in your case will be label + percentage.

Eg:

[chartlabels, {v: chartvalue, f: chartlabels+" "+((100 * chartvalue) / totalofvalues).toFixed(2)+"%"}]
Friable answered 2/9, 2021 at 7:4 Comment(1)
This is the correct solution, but the wording was not put clearly. "v" is the value which determines the size of the pie slice. "f" is the string which will be used as the pie slice label. Here is a better example of the data field to pass to the Google chart: data={[["Title", "#"],['a', {"v":2, "f":'2 out of 10'}],['b', {"v":3, "f":'3 out of 10'}],['c', {"v":5, "f":'5 out of 10'}]]}Jeroboam

© 2022 - 2024 — McMap. All rights reserved.