How to add Percentage and Total on the Legend of Google Pie Charts
Asked Answered
A

4

10

I have a page that displays data in a form of a Pie Chart. I use Google Charts to do this. Here's the code:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Goal Name', 'No. of times Requested'],
        ['Frank.net Life Cover', 226],
        ['Frank.net Hospital Cash Back', 147],
        ['Frank.net Salary Protection', 228],
        ['King Price Car Insurance', 328],
        ['Momentum Medical Aid', 493],
        ['Oplan Health Cover', 185],
        ['Youi Quote', 33],
        ]);

        var options = {
          title: 'Most Requested Sponsors'
        };

       var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
        chart.draw(data, options);
      }
    </script>
<div id="piechart2" style="width: 700px; height: 400px; position: relative;"></div>

And here's a working JS FIDDLE:

http://jsfiddle.net/yRdW3/

Now, I need help on displaying the percentage and total next to each sponsor name on the legend. I have no idea how to achieve this. I want it to look similar to this:

enter image description here

Achates answered 20/11, 2013 at 7:23 Comment(3)
This could help How to implement Google Pie chart(with legend display and corresponding values)Brundisium
@AntoJurkovic I've seen this earlier but I don't know where to put the code that the user suggested.Achates
Not sure but it seems that you have to select option legend: none and then build it yourself as a list and attach it to your chart: Google charts legend manipulationBrundisium
P
6

You can do this creating a column for tooltip and use your first column as legend. Check this FIDDLE

var dataArray = [
    ['Frank.net Life Cover', 226],
    ['Frank.net Hospital Cash Back', 147],
    ['Frank.net Salary Protection', 228],
    ['King Price Car Insurance', 328],
    ['Momentum Medical Aid', 493],
    ['Oplan Health Cover', 185,],
    ['Youi Quote', 33],
];

var total = getTotal(dataArray);

// Adding tooltip column  
for (var i = 0; i < dataArray.length; i++) {
  dataArray[i].push(customTooltip(dataArray[i][0], dataArray[i][1], total));
}

// Changing legend  
for (var i = 0; i < dataArray.length; i++) {
  dataArray[i][0] = dataArray[i][0] + " " + 
      dataArray[i][1] + " requests, " + ((dataArray[i][1] / total) * 100).toFixed(1) + "%"; 
}

// Column names
dataArray.unshift(['Goal Name', 'No. of times Requested', 'Tooltip']);

var data = google.visualization.arrayToDataTable(dataArray);

Using arrayToDataTable, you need to set the role tooltip in "Tooltip" column:

data.setColumnProperty(2, 'role', 'tooltip');
data.setColumnProperty(2, 'html', true);

Note: If you are creating the dataTable dynamically just call addColumn with this signature:

data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});

And in options add tooltip: { isHtml: true }:

var options = {
    title: 'Most Requested Sponsors',
    width: 900,
    height: 400,
    tooltip: { isHtml: true }
};
Porosity answered 5/5, 2016 at 17:53 Comment(0)
C
11

Check this fiddle example. It is your code with attached legend (idea from first comment, total calculation and some minor errors corrected).

Basic idea is to set legend option of chart to none and than you have to build your own legend.

If you load that code into browser the legend will be positioned to the right but you have to set proper CSS rules to get everything right (I'm not so familiar with CSS). But you have the basic idea how to do that.

And for different sets of legend colors you can check color brewer

Checky answered 20/11, 2013 at 9:41 Comment(1)
Thank you so much! I'll just modify the CSS.Achates
H
6

There is a way to do this utilizing the built-in legend. Essentially you can utilize the fact that the chart is rendered in SVG, and you can select and modify elements in the SVG the same way you select regular HTML elements. The basic idea is you:

  1. Select the labels in the chart's legend, and iterate through the collection. They are text tags, and you can figure out the selector using Firebug or Chrome Developer Tools.
  2. Use the index of the element to select the total of the associated row in the chart's DataTable (or insert your logic here for calculating whatever value you want to display).
  3. Modify the text of the label element to append your calculated value.

See my Codepen for a working example: http://codepen.io/breich/pen/mVPJwo

/**
 * Selector for chart element.
 */
var chartSelector = '#chart';

/**
 * Selector used to get label elements inside the rendered chart.
 * Your mileage may vary if you configure your chart different than
 * me. Use Firebug or Developer Tools to step through the SVG and
 * determine your label selector.
 */
var labelSelector = '> g:eq(1) g text';

/**
 * This is our data. For simplicity sake, doing inline and not AJAX.
 */
var data = [
  [ 'Apples', 10],
  [ 'Oranges', 20 ],
  [ 'Peaches', 30 ],
  [ 'Pears', 40 ],
  [ 'Bananas', 50 ]
];

// Load Google Charts 
google.load('visualization', '1.1', { packages: ['corechart', 'line'] });

// Callback when API is ready
google.setOnLoadCallback(function() {

  /*
   * Setup the data table with your data. 
   */
  var table = new google.visualization.DataTable({
    cols : [
      { id : 'name', label : 'Name', type : 'string' },
      { id : 'value', label : 'Value', type : 'number' }
    ]
  });

  // Add data to the table
  table.addRows( data );

  // Google Charts needs a raw element. I'm using jQuery to get the chart
  // Container, then indexing into it to get the raw element.
  var chartContainer = $(chartSelector)[0];

  // Create the Google Pie Chart
  var chart = new google.visualization.PieChart(chartContainer);

  // Draw the chart.
  chart.draw(table, { title : 'Classifications' });

  /*
   * This is the meat and potatoes of the operation. We really require
   * two things: #1) A selector that will get us a list of labels in the
   * legend, and #2) The DataTable powering the chart.  We'll cycle
   * through the labels, and use their index to lookup their value.
   * If you have some higher-level math you need to do to display a
   * different value, you can just replace my logic to get the count
   * with your's.
   */

  // The <svg/> element rendered by Google Charts
  var svg = $('svg', chartContainer );

  /*
   * Step through all the labels in the legend.
   */
  $(labelSelector, svg).each(function (i, v) {

    /*
     * I'm retrieving the value of the second column in my data table,
     * which contains the number that I want to display. If your logic
     * is more complicated, change this line to calculate a new total.
     */
    var total = table.getValue(i, 1);

    // The new label text.
    var newLabel = $(this).text() + '(' + total + ')';

    // Update the label text.
    $(this).text( newLabel );
  });

});
Hostess answered 17/12, 2015 at 13:5 Comment(0)
P
6

You can do this creating a column for tooltip and use your first column as legend. Check this FIDDLE

var dataArray = [
    ['Frank.net Life Cover', 226],
    ['Frank.net Hospital Cash Back', 147],
    ['Frank.net Salary Protection', 228],
    ['King Price Car Insurance', 328],
    ['Momentum Medical Aid', 493],
    ['Oplan Health Cover', 185,],
    ['Youi Quote', 33],
];

var total = getTotal(dataArray);

// Adding tooltip column  
for (var i = 0; i < dataArray.length; i++) {
  dataArray[i].push(customTooltip(dataArray[i][0], dataArray[i][1], total));
}

// Changing legend  
for (var i = 0; i < dataArray.length; i++) {
  dataArray[i][0] = dataArray[i][0] + " " + 
      dataArray[i][1] + " requests, " + ((dataArray[i][1] / total) * 100).toFixed(1) + "%"; 
}

// Column names
dataArray.unshift(['Goal Name', 'No. of times Requested', 'Tooltip']);

var data = google.visualization.arrayToDataTable(dataArray);

Using arrayToDataTable, you need to set the role tooltip in "Tooltip" column:

data.setColumnProperty(2, 'role', 'tooltip');
data.setColumnProperty(2, 'html', true);

Note: If you are creating the dataTable dynamically just call addColumn with this signature:

data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});

And in options add tooltip: { isHtml: true }:

var options = {
    title: 'Most Requested Sponsors',
    width: 900,
    height: 400,
    tooltip: { isHtml: true }
};
Porosity answered 5/5, 2016 at 17:53 Comment(0)
C
1
function drawChart() {

    var dataArray = [['Yes', <?php echo $member_yes_vote;?>],
                    ['No', <?php echo $member_no_vote;?>],
                    ['Total', 0],];

    var total = getTotal(dataArray);

    for (var i = 0; i < dataArray.length; i++)
    {                                    dataArray[i].push(customTooltip(dataArray[i][0], dataArray[i][1], total));
    }

    for (var i = 0; i < dataArray.length; i++) 
    {
        if(dataArray[i][0] == "Total")
        {
            dataArray[i][0] = dataArray[i][0] + " " + total + " Votes, " + ((total/total) * 100).toFixed(1) + "%";
        }
        else
        {
        dataArray[i][0] = dataArray[i][0] + " " + dataArray[i][1]+ " Votes, " + ((dataArray[i][1] / total) * 100).toFixed(1) + "%";
        } 
    }


    dataArray.unshift(['Vote Type', 'Number of Vote', 'Tooltip']);
    var data = google.visualization.arrayToDataTable(dataArray);
    data.setColumnProperty(2, 'role', 'tooltip');
    data.setColumnProperty(2, 'html', true);
    var options = {
                 chartArea:
                            {
                                                 left:40,top:20,width:'90%',height:'90%'
                            },
                is3D: true,
                slices: {0: {color: '#1a8ec5'}, 1:{color: '#da4638'}},
                pieSliceText: 'value-and-percentage',
                sliceVisibilityThreshold:0,
                tooltip: { isHtml: true }
            };

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

    function customTooltip(name, value, total) 
    {
      if(name == "Total")
    {
        return name + '<br/><b>' + total + ' (' + ((total/total) * 100).toFixed(1) + '%)</b>';
    }
    else
    {
    return name + '<br/><b>' + value + ' (' + ((value/total) * 100).toFixed(1) + '%)</b>';
    }
    }

    function getTotal(dataArray) 
    {
        var total = 0;
        for (var i = 0; i < dataArray.length; i++) 
        {
            if(dataArray[i][0] == "Total")
            {}
            else
            {
                total += dataArray[i][1];
            }
        }
        return total;
    }
    google.load('visualization', '1', {packages:['corechart'], callback: drawChart});

Here is the code which i have used to show the legend value with percentage and total field

Chesna answered 30/6, 2017 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.