Display total at top of legend in pie chart

137 views
Skip to first unread message

mani

unread,
Aug 18, 2014, 1:53:18 AM8/18/14
to google-visua...@googlegroups.com
Hi,

I am able to display the chart with user control but i have to display the total of all slices at the top of the legend.
how can i achive this,below is my code snippet

    <script type="text/javascript" src="googlejs/jsapi.js"></script>
<script src="googlejs/jquery.min.js"></script>
    <script type="text/javascript">
      google.load('visualization', '1.1', {packages: ['controls']});
    </script>
<link href="css/styles.css" rel="stylesheet" type="text/css">

    <script type="text/javascript">
      
        // Prepare the data
        
function drawVisualization() {
var json = $.ajax({
url: 'St_bk_chartdata.php', // make this url point to the data file
dataType: 'json',
async: false
}).responseText;
//var array = jQuery.parseJSON(json);
//var array  = JSON.parse(json);
//var data = google.visualization.arrayToDataTable(array);
var data = new google.visualization.DataTable(json);
var defaultRow = 1;
var defaultCol = 1;
        // Define category pickers for 'Country', 'Region/St' and 'City'
 var monthPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control0',
          'options': {
            'filterColumnLabel': 'Month',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false,
 'sortValues':false
            }
          },
    St: {
        selectedValues: [data.getValue(defaultRow, 0)]
    }
        });
        var StPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control1',
          'options': {
            'filterColumnLabel': 'St',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false
            }
          },
    St: {
        selectedValues: [data.getValue(defaultRow, 1)]
    }
        });
      
        var cityPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control2',
          'options': {
            'filterColumnLabel': 'District',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false
            }
          },
    St: {
        selectedValues: [data.getValue(defaultRow, 2)]
    }
        });
      
        var bkPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control3',
          'options': {
            'filterColumnLabel': 'bk',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false
            }
          },
    St: {
        selectedValues: [data.getValue(defaultRow, 3)]
    }
        });
      
        // Define a bar chart to show 'Population' data
        var barChart = new google.visualization.ChartWrapper({
          'chartType': 'PieChart',
          'containerId': 'chart1',
          'options': {
            'width': 900,
            'height': 700,
is3D: 'true',
            'chartArea': {top: 0, right: 0, bottom: 0}
          },
          // Configure the barchart to use columns 2 (City) and 3 (Population)
          'view': {'columns': [2, 3]}
        });
      
        // Create the dashboard.
        new google.visualization.Dashboard(document.getElementById('dashboard')).
          // Configure the controls so that:
          // - the 'Country' selection drives the 'Region' one,
          // - the 'Region' selection drives the 'City' one,
          // - and finally the 'City' output drives the chart
 bind(monthPicker, StPicker).
          bind(StPicker, barChart).
 //bind(cityPicker, barChart).
          //bind(cityPicker, bkPicker).
          //bind(bkPicker, barChart).
          // Draw the dashboard
          draw(data);
      }
      
 
      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
  <center>
<div id="parentDiv" >

<div id="headerDiv">
<div id="logoDiv" style="float:left;position:relative;">
<img align="left" height="100px" alt="St bk of tv logo" src="images/main.jpg" />
<img align="left" height="100px" alt="St bk of tv logo" src="images/fr.png" style="margin-left:44px;" />
</div>
</div>

<div id='barDiv'>
<div id='cssmenu'>
<ul>
  <li ><a href='index.php'><span style="color:white">Home</span></a></li>
  
  <li ><a href='index.php'><span style="color:white">Back</span></a></li> 
</ul>
</div>
</div>
    <div id="dashboard" style="padding-top:20px;">
      <table>
        <tr style='vertical-align: top'>
          <td style='width: 300px; font-size: 0.9em;'>
<div id="control0"></div>
            <div id="control1"></div>
            <div id="control2"></div>
            <!--<div id="control3"></div> -->
          </td>
          <td style='width: 600px,height: 900px'>
            <div style="float: left;" id="chart1"></div>
            <!--<div style="float: left;" id="chart2"></div>
            <div style="float: left;" id="chart3"></div> -->
          </td>
        </tr>
      </table>
    </div>
  </body>
</html>

Andrew Gallant

unread,
Aug 18, 2014, 7:51:42 PM8/18/14
to google-visua...@googlegroups.com
The charts do not support adding a total anywhere, but you can calculate it yourself, add it to your DOM, and use CSS to position the total over the chart wherever you need it.  You can calculate it like this:

google.visualization.events.addListener(barChart, 'ready', function () {
    var dt = barChart.getDataTable();
    var group = google.visualization.data.group(dt, [{
        type: 'number',
        column: 0,
        modifier: function () {
            return 0;
        }
    }], [{
        type: 'number',
        column: 3,
        aggregation: google.visualization.data.sum
    }]);
    var total = group.getValue(0, 1);
    // add total to your DOM
});

manish philip

unread,
Aug 19, 2014, 9:02:55 AM8/19/14
to google-visua...@googlegroups.com
Hi Andrew,

I added the piece of code but i am getting ReferenceError: barChart is not defined.
attaching the full code.
it would be great if you could tell me where am i going wrong.


    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>ce</title>
    <script type="text/javascript" src="googlejs/jsapi.js"></script>
<script src="googlejs/jquery.min.js"></script>
    <script type="text/javascript">
      google.load('visualization', '1.1', {packages: ['controls']});
    </script>
<link href="css/styles.css" rel="stylesheet" type="text/css">

    <script type="text/javascript">
      
        // Prepare the data
        
function drawVisualization() {
var json = $.ajax({
url: 'st_b_chartdata.php', // make this url point to the data file
dataType: 'json',
async: false
}).responseText;
var data = new google.visualization.DataTable(json);
var defaultRow = 1;
var defaultCol = 1;
        // Define category pickers for 'Country', 'Region/st' and 'City'
 var monthPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control0',
          'options': {
            'filterColumnLabel': 'Month',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false,
 'sortValues':false
            }
          },
    st: {
        selectedValues: [data.getValue(defaultRow, 0)]
    }
        });
        var stPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control1',
          'options': {
            'filterColumnLabel': 'st',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false
            }
          },
    st: {
        selectedValues: [data.getValue(defaultRow, 1)]
    }
        });
      
        var cityPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control2',
          'options': {
            'filterColumnLabel': 'District',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false
            }
          },
    st: {
        selectedValues: [data.getValue(defaultRow, 2)]
    }
        });
      
        var bPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control3',
          'options': {
            'filterColumnLabel': 'b',
            'ui': {
              'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': false
            }
          },
    st: {
        selectedValues: [data.getValue(defaultRow, 3)]
    }
        });
      
        // Define a bar chart to show 'Population' data
        var barChart = new google.visualization.ChartWrapper({
          'chartType': 'PieChart',
          'containerId': 'chart1',
          'options': {
            'width': 900,
            'height': 700,
is3D: 'true',
            'chartArea': {top: 0, right: 0, bottom: 0}
          },
          // Configure the barchart to use columns 2 (City) and 3 (Population)
          'view': {'columns': [2, 3]}
        });
      
        // Create the dashboard.
        new google.visualization.Dashboard(document.getElementById('dashboard')).
         
 bind(monthPicker, stPicker).
          bind(stPicker, barChart).
 
          draw(data);
      }
      
 
      google.setOnLoadCallback(drawVisualization);
 /////////////////////////////////////////////////////////your code////////////////////////////////////
google.visualization.events.addListener(barChart, 'ready', function () {
    var dt = barChart.getDataTable();
    var group = google.visualization.data.group(dt, [{
        type: 'number',
        column: 0,
        modifier: function () {
            return 0;
        }
    }], [{
        type: 'number',
        column: 3,
        aggregation: google.visualization.data.sum
    }]);
    var total = group.getValue(0, 1);
    // add total to your DOM
});
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
  <center>
<div id="parentDiv" >

<div id="headerDiv">
<div id="logoDiv" style="float:left;position:relative;">
<img align="left" height="100px" alt=" logo" src="images/sbt_main.jpg" />
<img align="left" height="100px" alt=" logo" src="images/fr.png" style="margin-left:44px;" />
</div>
</div>

<div id='barDiv'>
<div id='cssmenu'>
<ul>
  <li ><a href='index.php'><span style="color:white">Home</span></a></li>
 
  <li ><a href='index.php'><span style="color:white">Back</span></a></li> 
</ul>
</div>
</div>
    <div id="dashboard" style="padding-top:20px;">
      <table>
        <tr style='vertical-align: top'>
          <td style='width: 300px; font-size: 0.9em;'>
<div id="control0"></div>
            <div id="control1"></div>
            <div id="control2"></div>
          
          </td>
          <td style='width: 600px,height: 900px'>
            <div style="float: left;" id="chart1"></div>
            
          </td>
        </tr>
      </table>
    </div>
<div> </div>
  </body>
</html>

Thanks,
Manish


--
You received this message because you are subscribed to a topic in the Google Groups "Google Visualization API" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-visualization-api/FZPJFU5GW4k/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-visualizati...@googlegroups.com.
To post to this group, send email to google-visua...@googlegroups.com.
Visit this group at http://groups.google.com/group/google-visualization-api.
For more options, visit https://groups.google.com/d/optout.

Andrew Gallant

unread,
Aug 19, 2014, 7:09:07 PM8/19/14
to google-visua...@googlegroups.com
You need to add that code right after the code block where you create the barChart ChartWrapper object:

var barChart = new google.visualization.ChartWrapper({
    'chartType': 'PieChart',
    'containerId': 'chart1',
    'options': {
        'width': 900,
        'height': 700,
        is3D: 'true',
        'chartArea': {top: 0, right: 0, bottom: 0}
    },
    // Configure the barchart to use columns 2 (City) and 3 (Population)
    'view': {'columns': [2, 3]}
});

google.visualization.events.addListener(barChart, 'ready', function () {
    var dt = barChart.getDataTable();
    var group = google.visualization.data.group(dt, [{
        type: 'number',
        column: 0,
        modifier: function () {
            return 0;
        }
    }], [{
        type: 'number',
        column: 3,
        aggregation: google.visualization.data.sum
    }]);
    var total = group.getValue(0, 1);
    // add total to your DOM
});

Also, where I have the comment "add total to your DOM", you need to write code to add the total to your DOM.
To unsubscribe from this group and all its topics, send an email to google-visualization-api+unsub...@googlegroups.com.

manish philip

unread,
Aug 23, 2014, 1:36:30 PM8/23/14
to google-visua...@googlegroups.com
Hi Andrew,

Thanks for your quick response.

i want to understand how this code works so that i can implement in other situations as well.
in the below code snippet i was trying in jsfiddle.but the chart broke,here also i am trying to get the total .
chart works perfectly without the commented section (total starts total ends)


google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

var pie, pieopts; // Cache this instance to allow redrawing without leaking.
function drawChart() {
    var theData = [{Server:'CMSBOS01', Count:71},
    {Server:'CMSBOS02', Count:77},
    {Server:'CMSBOS03', Count:78}];
    
    $("#divFun").text(JSON.stringify(theData));
    
    var piedata = new google.visualization.DataTable();
    piedata.addColumn('string', 'Server');
    piedata.addColumn('number', 'Trans');
    piedata.addRows(theData.length);
    
    for (var LCV = 0; LCV < theData.length; LCV++) {
        piedata.setValue(LCV, 0, theData[LCV].Server);
        piedata.setValue(LCV, 1, theData[LCV].Count);
    }
    
    pieopts = pieopts || {
        title: 'Server Stats',
        is3D: true,
        chartArea: { left: 10, top: 25, width: 600, height: 200 },
        height: '100%',
        width: '50%',
        backgroundColor: { stroke: 'black', strokeWidth: 3 },
        legend: { position: 'right', textStyle: { fontSize: 9, alignment: 'start' } }
    };
        
    pie = pie || new google.visualization.PieChart(document.getElementById('chart_div'));
/////total starts/////
    google.visualization.events.addListener(pie, 'ready', function () {
    var dt = pie.getDataTable();
    var group = google.visualization.data.group(dt, [{
        type: 'number',
        column: 1,
        modifier: function () {
            return 0;
        }
    }], [{
        type: 'number',
        column: 1,
        aggregation: google.visualization.data.sum
    }]);
    var total = group.getValue(0, 1);
        alert(total);
/////total ends/////
    pie.draw(piedata, pieopts);
}



To unsubscribe from this group and all its topics, send an email to google-visualizati...@googlegroups.com.

Andrew Gallant

unread,
Aug 23, 2014, 9:13:28 PM8/23/14
to google-visua...@googlegroups.com
The "ready" event handler takes the data used by the PieChart and groups it using the google.visualization.data.group function.  This function takes 3 arguments:

google.visualization.daat.group(dataTable, groupingColumns, aggregationColumns);

dataTable is the DataTable to group (dt in the example).  groupingColumns is an array of columns to group by.  Since you want to provide a sum of all rows, you need to use a column that contains values that are all exactly the same, so they all group together; that is what this does:

[{
    type: 'number',
    column: 1,
    modifier: function () {
        return 0;
    }
}]

The column parameter tells the group function which column to group by, and the modifier function tells the group function how to modify the data before grouping.  Since you want all values the same, we set type to "number" and return 0 for all rows (it could be any value or data type, as long as all of the values are the same).  Importantly, the column here must be a column that you are not going to aggregate data from, as the modifier function changes the values used in the aggregation as well.  You did not specify what wasn't working, but I would hazard a guess to say that your totals were coming out as 0, which is because your grouping and aggregation columns were the same.  Try changing column to 0 instead of 1.

aggregationColumns is an array of columns to aggregate:

[{
    type: 'number',
    column: 1,
    aggregation: google.visualization.data.sum
}]

This tells the group function to aggregate column 1 using the google.visualization.data.sum function, and that the results of the aggregation will be type "number".  The aggregation function can be any function that takes an array of values and returns a single value of the appropriate type.  google.visualization.data.sum is one of the aggregation functions built in to the Visualization API, but you could also have a function like this that would be equivalent:

[{
    type: 'number',
    column: 1,
    aggregation: function (values) {
        var sum = 0;
        for (var i = 0; i < values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
}]

Does that help?
To unsubscribe from this group and all its topics, send an email to google-visualization-api+unsubscr...@googlegroups.com.
To post to this group, send email to google-visua...@googlegroups.com.

manish philip

unread,
Aug 24, 2014, 8:35:42 AM8/24/14
to google-visua...@googlegroups.com
Hi Andrew,

thanks for the details,i tried to implement the same in js fiddle link below


code works on commenting the aggregation part.

is the initialization incorrect?




To unsubscribe from this group and all its topics, send an email to google-visualizati...@googlegroups.com.

Andrew Gallant

unread,
Aug 24, 2014, 11:29:30 AM8/24/14
to google-visua...@googlegroups.com
You have a syntax error in that code: you are missing the closing }); for the addListener call.  Also, since your example uses a plain chart object instead of a ChartWrapper, you cannot use the #getDataTable method - you must reference the base DataTable instead (and actually wouldn't need to use the event listener at all; that is just for handling cases where the chart is part of a Dashboard).

To unsubscribe from this topic, visit <a href
...

manish philip

unread,
Aug 25, 2014, 7:00:11 AM8/25/14
to google-visua...@googlegroups.com
Thanks Andrew,

it works as expected, since loading of chart takes time i am displaying a loading image,but as soon as page starts getting reponse loading image vanishes,eventhough chart is not displayed fully.

does chart have any loading message display property untill chart is loaded?


To unsubscribe from this group and all its topics, send an email to google-visualizati...@googlegroups.com.

Andrew Gallant

unread,
Aug 25, 2014, 8:49:54 AM8/25/14
to google-visua...@googlegroups.com
The charts do not have a loading message.  You could change your loading code to turn off the loading image in the chart's "ready" event handler instead of turning it off when the data finishes loading.
To unsubscribe from this group and all its topics, send an email to google-visualization-api+unsub</
...

manish philip

unread,
Sep 9, 2014, 6:43:18 AM9/9/14
to google-visua...@googlegroups.com
Hi Andrew,

    var formatter = new google.visualization.NumberFormat({prefix: 'Rs.'});
     formatter.format(data, 3);


I am using above formatter for display currency, it displays in ###,###.##
sets of three

but i want to display in custom format.
eg.  #,##,##,##,###.##

i could not find any example ,please advise if it is possible?

Thanks,
Manish



Andrew Gallant

unread,
Sep 9, 2014, 9:17:15 AM9/9/14
to google-visua...@googlegroups.com
You should be able to use an ICU decimal pattern to format the number:

var formatter = new google.visualization.NumberFormat({pattern: 'Rs\'.\' #,##,###.##'}); 
formatter.format(data, 3);

However, the NumberFormatter does not handle grouping symbols correctly.  This pattern should format 123456789.98 as "Rs. 12,34,56,789.98", but it actually formats it as "Rs. 1,23,456,789.98".  I filed a bug report on this.
...
Reply all
Reply to author
Forward
0 new messages