javascriptjquerygoogle-visualizationpie-chartgoogle-pie-chart

Show different suffix in Google Piechart


I have a piechart showing the result the total bandwidth of uplink/downlink.

Right now, they suffix is GB.

enter image description here

I struggling trying to display their suffix different. Example,


I have

<script>

google.setOnLoadCallback(drawChart);
function drawChart() {

  console.log(color['downlink']);

  var data = google.visualization.arrayToDataTable([
    ['Task', 'Bandwith'],
    ['Downlink', ({{$t_down_bytes}})],
    ['Uplink', ({{$t_up_bytes}})]
  ]);

  var options = {
    legend: 'buttom',
    pieSliceText: 'value', // text | none
    title: 'Total Bandwith Usage',
    colors: [color['downlink'], color['uplink']],
    width:'100%',
    height: 400,
    slices: {
      1: {offset: 0.1}
    },

  };

  var formatter = new google.visualization.NumberFormat({
    fractionDigits:2,
    suffix: ' GB'
  });

  formatter.format(data, 1);

  var chart = new google.visualization.PieChart(document.getElementById('private'));
  chart.draw(data, options);
}

</script>

I can someone can shed some light on this.

Any hints / suggestions on this will be much appreciated !


Solution

  • One way is just doing it yourself: (Correct way to convert size in bytes to KB, MB, GB in Javascript might help)

        var data = google.visualization.arrayToDataTable([
          ['Task', 'Bandwith'],
          ['Downlink', {v:6.4672328, f:"6.46 GB"}],
          ['Uplink', {v:9.40213213, f:"9.40 KB"}]
        ]);
    

    Note that v is the "real" value google uses to draw and f is the formatted value it will show

    If you want to keep your google formatter, another way is to add this line after your formatter.format(data, 1);

    data.setFormattedValue(1,1,data.getFormattedValue(1,1).replace("GB","KB"))
    

    Which sets the formattedValue of row 1, column 1

    Update taking into account you want to use a mix of both:

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Bandwith'],
      ['Downlink', $t_down_bytes],
      ['Uplink', $t_up_bytes],
     ]);
    
    var formatter = new google.visualization.NumberFormat({
        fractionDigits:2
    });
    
    formatter.format(data, 1);
    
    data.setFormattedValue(0,1,data.getFormattedValue(0,1) + ' {{$t_down_bytes_suffix}}')
    
    data.setFormattedValue(1,1,data.getFormattedValue(1,1) + ' {{$t_up_bytes_suffix}}')
    

    For more info on setFormattedValue and getFormattedValue check

    Google Datatable Documentation