google-visualizationpygooglechart

Google halfdonut pie chart: is it possible to set total percentage?


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


Solution

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