I have a Pie Charts generated by Google Chart API. The code for the chart goes as Below
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1()
{
var data = google.visualization.arrayToDataTable([
['Location', 'Value'],
["Location A", 20 ],
["Location B", 32],
["Location C", 12],
["Location D", 20],
["Location E", 2],
["Location F", 20],
["Location H", 10]
]);
var options = {
colors : ['#00918c', '#d0c500','#945a94', '#84ac43', '#ea8c1c', '#006daf', '#c54d4d'],
is3D : 'false',
isHTML : 'false',
height : 200,
width : 285,
backgroundColor : "transparent",
chartArea : {left:0,top:0,width:"100%",height:"100%"},
legend : {position: 'right', alignment: "end"}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
The Link for the chart is as Below
Click to see Chart
I want to capture the event in the chart when they click any pie area.
Suppose if they click on Location A pie in pie chart I want a function that displays alert message as Location A Clicked and same for other pie's in chart.
Thanks for reply
I added the code below and its working fine now.
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
function selectHandler()
{
var selectedItem = chart.getSelection()[0];
if (selectedItem)
{
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
See the link for Binding Events in google pie chart.
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
} </script>
Related
Using Google pie charts
Fiddle
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 20],
['Eat', 2],
['Commute', 2],
['Watch TV', 2]
]);
How can I get the 'Hours per Day' to show in the chart itself. Now it is showing in the tooltip mouseover. For example mouseover on Eat will show 2. When I save/print the chart I can't get these items. How to show this on the chart?
the pieSliceText configuration option allows you to change what appears on each slice
to get the value of the row, use...
pieSliceText: 'value'
also, if the chart isn't big enough, it will omit the label
there are several ways to size the chart
you can style the div container,
or set the height and width in the options
also, google recommends waiting on the chart's 'ready' event,
before calling any methods, including getImageURI
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 20],
['Eat', 2],
['Commute', 2],
['Watch TV', 2]
]);
var options = {
height: 400,
legend: {
position: 'labeled',
textStyle: {
color: 'blue'
}
},
pieSliceText: 'value',
title: 'My Daily Activities',
width: 800
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
document.getElementById('image_div').innerHTML = '<img alt="Chart" src="' + chart.getImageURI() + '">';
});
chart.draw(data, options);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="image_div"></div>
This code:
chart = new google.charts.Bar(document.getElementById('chart'));
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', '');
dataTable.addColumn('number', 'Value');
dataTable.addColumn({type: 'string', role: 'tooltip', p: {'html': true}});
var rows = [
['U.S.', 2, "tool"],
['France', 10, "tip"]
];
dataTable.addRows(rows);
chart.draw(dataTable);
does not result in a custom tooltip.
Strangely it works with other chart types.
Do you know why please?
[edit] Apparently this is not possible. Is there any other way to put a "%" symbol in the tooltip, like in this screenshot?
The tooltip should show the formatted value by default.
Using object notation for your values, you can provide a formatted value (f:)
along with the required value (v:)...
you can also use dataTable.setFormattedValue(...) after the table is loaded...
Example...
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
function drawChart() {
chart = new google.charts.Bar(document.getElementById('chart'));
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', '');
dataTable.addColumn('number', 'Value');
var rows = [
['U.S.', {v: 2, f: '2%'}], // add %
['France', {v: 10, f: '10%'}], // add %
['Germany', {v: 15, f: 'whatever we want'}] // add whatever we want
];
dataTable.addRows(rows);
chart.draw(dataTable);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
I've 2 google charts on one page and both are displayed correctly. The problem is when I set fontName of both charts to 'Open Sans', only one chart is displayed. If both charts have some other font like 'Arial', then both are displayed. Also, if fontName for one chart is 'Open Sans' and 'Arial' for other, both charts are displayed. Error is only with 'Open Sans' for both charts. I've included Below is my code snippet. Can't get a solution to this. Please help. Thanks in advance..!!
<script type="text/javascript">
function commodityChart(){
// Load the Visualization API and the piechart package.
google.load('visualization', '1.1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
for($i=0;$i<count($data);$i++){
if($data[$i]->SEGMENT == 'COMMODITY'){
echo "['" . $data[$i]->PARAMETER . "'," . $data[$i]->AMOUNT . "],";
}
}
?>
]);
var formatter = new google.visualization.NumberFormat({prefix: '₹', format:'##,##,###.00'} );
formatter.format(data, 1);
// Set chart options
var options = {pieHole: 0.4,
fontSize: 13,
fontName: 'Open Sans',
is3D : true,
pieSliceText: 'value',
sliceVisibilityThreshold: 0,
// pieStartAngle: 100,
slices: {0: {offset: 0.3}},
//fontName: 'Open Sans',
legend: {position: 'right', alignment:'end'},
colors: ['#9bc53d', '#FF9900'],
'width':600,
// chartArea:{left:30,top:20,width:'70%',height:'75%'},
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('gchart_pie_2'));
chart.draw(data, options);
}
}
</script>
<script type="text/javascript">
function equityChart(){
// Load the Visualization API and the piechart package.
google.load('visualization', '1.1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart1);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart1() {
// Create the data table.
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'type');
data1.addColumn('number', 'amount');
//data.addColumn({type: 'string', role: 'tooltip'});
data1.addRows([
<?
for($i=0;$i<count($data);$i++){
if($data[$i]->SEGMENT == 'EQUITY'){
echo "['" . $data[$i]->PARAMETER . "'," . $data[$i]->AMOUNT . "],";
}
}
?>
]);
var formatter = new google.visualization.NumberFormat({prefix: '₹', format:'##,##,###.00'} );
formatter.format(data1, 1);
// Set chart options
var options1 = {pieHole: 0.4,
is3D: true,`enter code here`
legend: {position: 'right', alignment:'end'},
//fontSize: 13,
fontName: 'Open Sans',
forceIFrame: false,
// pieSliceBorderColor: 'red',
pieSliceText: 'value',
//pieSliceTextStyle: {fontName: 'Open Sans', fontSize: 13},
chartArea:{left:20,top:20,width:'70%',height:'75%'},
// pieStartAngle: 20,
// slices: {0: {offset: 0.4}},
sliceVisibilityThreshold: 0,
// colors: ['#5bc0eb','#fde74c', '#9bc53d', '#e55934', '#fa7921'],
colors: ['#9bc53d','#fde74c', '#e55934', '#5bc0eb', '#FF9900'],
//tooltip: {isHtml: true},
'width':600,
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart1 = new google.visualization.PieChart(document.getElementById('gchart_pie_1'));
chart1.draw(data1, options1);
}
}
enter code here
Try drawings the charts one at a time, that seems to fix the problem...
Here, I use the ready event to wait for the first chart to draw, then draw the second.
google.load('visualization', '1.1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
commodityChart();
}
function commodityChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Pepperoni', 33],
['Hawaiian', 26],
['Mushroom', 22],
['Sausage', 10],
['Anchovies', 9]
]);
var options = {
pieHole: 0.4,
fontSize: 13,
fontName: 'Open Sans',
is3D: true,
pieSliceText: 'value',
sliceVisibilityThreshold: 0,
slices: {
0: {
offset: 0.3
}
},
legend: {
position: 'right',
alignment:'end'
},
colors: [
'#9bc53d',
'#FF9900'
],
width: 600,
height: 500
};
var chart = new google.visualization.PieChart(document.getElementById('gchart_pie_2'));
google.visualization.events.addListener(chart, 'ready', equityChart);
chart.draw(data, options);
}
function equityChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'type');
data1.addColumn('number', 'amount');
data1.addRows([
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options1 = {
pieHole: 0.4,
is3D: true,
legend: {
position: 'right',
alignment: 'end'
},
fontName: 'Open Sans',
forceIFrame: false,
pieSliceText: 'value',
chartArea: {
left: 20,
top: 20,
width: '70%',
height: '75%'
},
sliceVisibilityThreshold: 0,
colors: [
'#9bc53d',
'#fde74c',
'#e55934',
'#5bc0eb',
'#FF9900'
],
width: 600,
height: 500
};
var chart1 = new google.visualization.PieChart(document.getElementById('gchart_pie_1'));
chart1.draw(data1, options1);
}
<script src="https://www.google.com/jsapi"></script>
<div id="gchart_pie_1"></div>
<div id="gchart_pie_2"></div>
I have created a donut chart from Google Charts API. When clicking on each slice, it should increase by 10 units and decrease the adjacent slice (clockwise) by 10 units. What I have thus far is a alert popup that explains this, but I would like to redraw the chart with the new values.
Here is my code:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Option');
data.addColumn('number', 'Value');
data.addRows([
['Option A', 40],
['Option B', 30],
['Option C', 30]
]);
// Set chart options
var options = {
height: 300,
fontName: 'Lato, sans-serif',
title: 'Values per option',
titleTextStyle: {
color: '#5a5a5a',
fontSize: 20,
bold: true,
align: 'center'
},
pieHole: 0.6,
slices: {
0: {color: 'red'},
1: {color: 'blue'},
2: {color: 'green'}
},
legend: {
position: 'bottom',
textStyle: {
color: '#5a5a5a',
fontSize: 14
}
},
enableInteractivity: true,
pieSliceText: 'none'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem && selectedItem.row <2) {
var activeTrait = data.getValue(selectedItem.row, 0);
activePerc = data.getValue(selectedItem.row, 1);
activePercNew = parseInt(activePerc)+10
adjaceTrait = data.getValue(selectedItem.row+1, 0);
adjacePerc = data.getValue(selectedItem.row+1, 1);
adjacePercNew = parseInt(adjacePerc)-10
alert(activeTrait + ' has a value of ' + activePerc + '%. The new value will now be set to ' + activePercNew + '% and ' + adjaceTrait + ' will be corrected to ' + adjacePercNew + '%.');
}
if (selectedItem && selectedItem.row == 2) {
var activeTrait = data.getValue(selectedItem.row, 0);
activePerc = data.getValue(selectedItem.row, 1);
activePercNew = parseInt(activePerc)+10
adjaceTrait = data.getValue(selectedItem.row-2, 0);
adjacePerc = data.getValue(selectedItem.row-2, 1);
adjacePercNew = parseInt(adjacePerc)-10
alert(activeTrait + ' has a value of ' + activePerc + '%. The new value will now be set to ' + activePercNew + '% and ' + adjaceTrait + ' will be corrected to ' + adjacePercNew + '%.');
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:800; height:300"></div>
</body>
</html>
I would just like to resize the selected and adjacent slices by clicking on a single slice. Not sure if I should create a var newdata with the changed values and use chart.draw(newdata, option)?
Yeah you're pretty much there, and you're definitely on the right track with your answer. You can use data.setValue() to adjust your values then you would have something like this in your second "if" statement:
data.setValue(selectedItem.row,1, activePercNew);
data.setValue(selectedItem.row-2,1, adjacePercNew);
chart.draw(data, options);
// the thing we just clicked on was redrawn so it lost its handler, reinstate it:
google.visualization.events.addListener(chart, 'select', selectHandler);
And the same in the first but with selectedItem.row+1 instead of selectedItem.row-2. Or, ideally, tidy that section up a little so the two if statements figure out which things you're referring to and then one bit of code does the redraw. For example, here's an adjusted handler function which also doesn't rely on there being 3 sections:
function selectHandler() {
var selectedItem = chart.getSelection()[0];
var numRows = data.getNumberOfRows();
// verify the selection isn't inexplicibly invalid
if (selectedItem && selectedItem.row < numRows && selectedItem.row >= 0) {
// find the two items we're looking at
var curItem = selectedItem.row;
// we either want selected.row + 1 or we want 0 if the selected item was the last one
var otherItem = selectedItem.row == numRows - 1 ? 0 : selectedItem.row + 1;
// calculate the new values
var activePerc = data.getValue(curItem , 1);
var activePercNew = parseInt(activePerc)+10;
var adjacePerc = data.getValue(otherItem , 1);
var adjacePercNew = parseInt(adjacePerc )-10;
// update the chart
data.setValue(curItem,1, activePercNew);
data.setValue(otherItem,1, adjacePercNew);
chart.draw(data, options);
// the thing we just clicked on was redrawn so it lost its handler, reinstate it:
google.visualization.events.addListener(chart, 'select', selectHandler);
}
}
You might want to then also consider what should happen if a value is forced right to zero - with this solution it'll disappear from the chart, and then the next click will force an invalid negative value.
Is it possible to switch between chart types (pie and column) by clicking on the according button?
For example I want to have two buttons and once I click on the first button it will display pie chart.
This is pretty straight forward
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var piechart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
onyour click handler simply replace
var barchart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);