2

I made half a donut chart with Google charts and I have a problem that the sum of visible percentage is equal to 50%. Is there any possible solution ?

Image of my chart

Lukas
  • 610
  • 7
  • 16

1 Answers1

8

you can override the text displayed on the slice by using the following config option...

pieSliceText: 'value'

then in the data, set the formatted value of the cells to the correct percentage...

var data = [
  ['Task', 'Hours'],

  // use formatted values
  ['A', {v: 19.2, f: '38.4%'}],
  ['B', {v: 30.8, f: '61.6%'}],

  [null, 50]
];

the following working snippet uses the same approach,
but calculates the correct percentages,
rather than hard-coding...

google.charts.load('current', {
  callback: function () {
    var data = [
      ['Task', 'Hours'],
      ['A',  19.2],
      ['B',  30.8],
      [null, 50.0]
    ];

    var total = 0;
    for (var i = 1; i < data.length; i++) {
      if (data[i][0] !== null) {
        total += data[i][1];
      }
    }

    var numberFormat = new google.visualization.NumberFormat({
      pattern: '#,##0.0',
      suffix: '%'
    });

    var dataTable = google.visualization.arrayToDataTable(data);
    for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
      if (dataTable.getValue(i, 0) !== null) {
        dataTable.setFormattedValue(i, 1, numberFormat.formatValue(((dataTable.getValue(i, 1) / total) * 100)));
      }
    }

    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

    var options = {
      height: 400,
      chartArea: {
        top: 24
      },
      colors: ['#8BC34A', '#64B5F6'],
      legend: 'none',
      pieHole: 0.4,
      pieStartAngle: 270,
      pieSliceText: 'value',
      slices: {
        2: {
          color: 'transparent'
        }
      },
      theme: 'maximized',
      width: 400
    };

    chart.draw(dataTable, options);
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
WhiteHat
  • 59,912
  • 7
  • 51
  • 133
  • I am facing this problem right now. My problem is because I have dynamic data. Do you suggest anything? – ARNON Feb 07 '21 at 22:22
  • 1
    you can use the above approach by using the `setFormattedValue` method after building the data table. – WhiteHat Feb 08 '21 at 12:23