Search code examples
javascriptchartsgoogle-visualizationpie-chart

how to display label and values only on google pie chart legend with data from mysql db


I am using google charts API to display pie chart and I want the legend to display only the label and values and I'm stucked, most of the answers I searched includes percentage. How can I do this?

My code below:

PHP

$table         = array();
$table['cols'] = array(
    //Labels for the chart, these represent the column titles
    array('id' => '', 'label' => 'Country', 'type' => 'string'),
    array('id' => '', 'label' => 'Number of Devices', 'type' => 'number')
); 

$rows = array();
foreach($exec as $row){
    $temp = array();

    //Values
    $temp[] = array('v' => (string) $row['Country']);
    $temp[] = array('v' => (int) $row['Number of Devices']); 
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows; 
$jsonTable = json_encode($table);
echo $jsonTable

JavaScript

google.charts.load('current', {'packages':['corechart']});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {

  var PieChart_options = {
      title: 'Number of Devices per country',
      pieSliceText: 'value',
      width: 900, 
      height: 500
    };

 var data = new google.visualization.DataTable(<?=$jsonTable?>);

  var chart = new google.visualization.PieChart(document.getElementById('pie_div'));
  chart.draw(data, PieChart_options);

}

I want to create like this one: pie chart with label and value on legend


Solution

  • the chart can be modified, once the 'ready' event fires

    be sure to set the event listener, before drawing the chart

    the legend labels should appear in the same order as the data provided

    the following snippet finds the legend labels by checking attribute values

    then adds the value from the data...

    google.charts.load('current', {
      callback: function () {
        var data = new google.visualization.DataTable({
          "cols": [
            {"label": "Country", "type": "string"},
            {"label": "# of Devices", "type": "number"}
          ],
          "rows": [
            {"c": [{"v": "Canada"}, {"v": 33}]},
            {"c": [{"v": "Mexico"}, {"v": 33}]},
            {"c": [{"v": "USA"}, {"v": 34}]}
          ]
        });
    
        var container = document.getElementById('chart_div');
        var chart = new google.visualization.PieChart(container);
    
        google.visualization.events.addListener(chart, 'ready', function () {
          var rowIndex = 0;
          Array.prototype.forEach.call(container.getElementsByTagName('text'), function(label) {
            // find legend labels
            if ((label.getAttribute('text-anchor') === 'start') && (label.getAttribute('fill') !== '#ffffff')) {
              label.innerHTML += ' (' + data.getValue(rowIndex++, 1) + ')';
            }
          });
        });
    
        chart.draw(data, {
          height: 400,
          width: 600
        });
      },
      packages:['corechart']
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart_div"></div>