Search code examples
javascriptchartsgoogle-visualizationpie-chart

Google pie chart: rounding issue with 2 decimal percentages


I'm facing an issue with Google Charts. I want a pie chart showing all values with a labeled legend, including very small values that are below 0.1%.

Say i have the following data:

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     66],
      ['Sleep',    33.95],
      ['Eat', 0.05]
    ]);

(Total matches up to 100)

The problem now is that when calculating the percentages, Google Charts is rounding the values, causing 33.95 to become 34 and thus 0.05 becoming 0.

Example here: https://jsfiddle.net/4qe7h21s/

Is there any way to let the Charts engine create percentages with 2 decimals instead of 1 decimal?


Solution

  • since no option to change format or precision of the percentage

    first, need to set
    sliceVisibilityThreshold: 0.0001

    so 'Eat' doesn't fall into 'Other'

    next, provide custom formatted values in the data
    {v: 66, f: '66.00%'}

    set pieSliceText and tooltip.text to 'value'

    since the slice for 'Eat' is so small, use
    tooltip.trigger: 'selection'

    see following example, slices show correct percentage

    click on legend item for 'Eat' to see tooltip

    google.charts.load('current', {
      callback: function () {
        new google.visualization.PieChart(document.getElementById('chart_div')).draw(
          google.visualization.arrayToDataTable([
            ['Task',  'Hours per Day'],
            ['Work',  {v: 66, f: '66.00%'}],
            ['Sleep', {v: 33.95, f: '33.95%'}],
            ['Eat',   {v: 0.05, f: '0.05%'}]
          ]),
          {
            height: 400,
            legend: {
              position: 'right'
            },
            pieSliceText: 'value',
            sliceVisibilityThreshold: 0.0001,
            title: 'My Daily Activities',
            tooltip: {
              showColorCode: true,
              text: 'value',
              trigger: 'selection'
            },
            width: 600
          }
        );
      },
      packages: ['corechart', 'table']
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>