Google chart animation is not visible when chart data is changed - javascript

I am having trouble getting the Google chart animations to work properly. I think the problem is that the chart keeps getting redrawn instead of just the data updated, but I'm not sure how to remedy this based on Google's example code and my limited knowledge of JavaScript. I do not want to include a button to update the chart as the chart will eventually update data dynamically from a data source. How do I update my chart to properly display the animations on data change?
Reference: https://developers.google.com/chart/interactive/docs/animation
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="pizzaChart" style="overflow: hidden"></div>
<p id="logger"></p>
<script>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var mushroomData = Math.floor(Math.random() * 11);
document.getElementById("logger").innerHTML = mushroomData;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', mushroomData],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
var options = {
title: 'How Much Pizza I Ate Last Night',
width: '100%',
animation: {duration: 1000, easing: 'out'}
};
var chart = new google.visualization.ColumnChart(document.getElementById('pizzaChart'));
chart.draw(data, options);
}
setInterval(drawChart, 1000);
</script>
</body>
</html>

in order to animate the chart from one dataset to the next,
you need to keep a reference to the same chart.
instead of creating a new chart each time it is drawn.
see following example...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(initChart);
var chart;
function initChart() {
chart = new google.visualization.ColumnChart(document.getElementById('pizzaChart'));
drawChart();
}
function drawChart() {
var mushroomData = Math.floor(Math.random() * 11);
document.getElementById("logger").innerHTML = mushroomData;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', mushroomData],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
var options = {
title: 'How Much Pizza I Ate Last Night',
width: '100%',
animation: {duration: 1000, easing: 'out'}
};
chart.draw(data, options);
}
setInterval(drawChart, 1000);
note: google pie charts do not animate

Related

How to set a Percentage of an Amount of work done using Google Charts

I've look over all the documentation and i cannot find where is specifically documents what type of data to pass to the pie chart to show what slice of a percentage is an amount that still needs work done when considering the pie is a whole of 100%.
Lets say we've got these following task.
1. Database
2. Front end
3. Web Design
Database is 45% done
Front end is 35% done
Web Design is 60 percent done.
I am able to pass percentages and decimals to the data table but I am getting lost when they're passing in number of 1, 3, 2 and so on.
The goal is for investors to see the amount of work left to do in the pie chart, how should i do this by working with decimals or percentages?
I might not be asking the correctly because if the amount of work left to be done when starting at 100% would not work.
How is it that i can display to the investor based on about 10 slices that make up 100% of the work to do, and what data should i pass to this type of pie?
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Assamese', 13], ['Bengali', 83], ['Bodo', 1.4],
['Dogri', 2.3], ['Gujarati', 46], ['Hindi', 300],
['Kannada', 38], ['Kashmiri', 5.5], ['Konkani', 5],
['Maithili', 20], ['Malayalam', 33], ['Manipuri', 1.5],
['Marathi', 72], ['Nepali', 2.9], ['Oriya', 33],
['Punjabi', 29], ['Sanskrit', 0.01], ['Santhali', 6.5],
['Sindhi', 2.5], ['Tamil', 61], ['Telugu', 74], ['Urdu', 52]
]);
var options = {
title: 'Indian Language Use',
legend: 'none',
pieSliceText: 'label',
slices: { 4: {offset: 0.2},
12: {offset: 0.3},
14: {offset: 0.4},
15: {offset: 0.5},
},
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
So, once again i would like to use a pie chart for investors to look at to see an amount of work done.
Here is my fiddler.
Check Fiddler
Pass a variable into the pie chart's data section that represents work not yet completed. You could hardcode this yourself, or use a value that is calculated by subtracting completed work from the total.
E.g.
Database = 45;
Backend = 35;
Web Design = 60;
Work Remaining = 300 - [Database + Backend + Web Design];
You could have its colour in the pie chart set to grey, and leave its name blank.
see following working snippet...
google.charts.load('current', {
callback: function () {
drawChart('Database', 45);
drawChart('Front-end', 35);
drawChart('Web Design', 60);
},
packages:['corechart']
});
function drawChart(task, complete) {
var data = google.visualization.arrayToDataTable([
['Task', task],
['Complete', complete],
['Remaining', 100 - complete]
]);
var options = {
title: task,
pieHole: 0.3
};
var container = document.body.appendChild(document.createElement('div'));
var chart = new google.visualization.PieChart(container);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>

multiple google charts with separate options

I'm starting out with google charts (gauges)
i need to put multiple gauges on the same page, each with a different max value (which is set in options)
but what it seems is that the options is somehow global for all charts
they all become 0 to 1
here's my code
<script type="text/javascript">
google.charts.load('current', { 'packages': ['gauge'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.getJSON("Dashboard/GaugeData", function (jsn) {
var dGauges = $('#gauges');
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
$.each(jsn, function (i, item) {
data.addRow([item.Label, item.Pending]);
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, {
width: 400, height: 400,
redFrom: 90, redTo: 100,
yellowFrom: 75, yellowTo: 90,
minorTicks: 5, max: item.Max
});
});
});
} setInterval(function () {
drawChart();
}, 10000);
</script>
please note that i cannot prepare a new div for each chart, since the amount of charts is dynamic (from json)
i believe i could create the divs dynamically and then check before each refresh if i need to add the div or remove etc... but i'm hoping there's a better way

Google charts tooltip with pie chart isn't shown

Im using google chart to drow pie chart. I need to change slice offset value slice onhover event. I wrote some code but the problem is chart does not display tooltip.
// 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]
]);
var options = {
is3D: true,
tooltip: { textStyle: { color: '#000000' }, showColorCode: true }
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandlerOver(e) {
//alert('selectHandlerOver');
var row = e.row;
var s = $.parseJSON('{ ' +
'"is3D": "true",' +
'"slices": { "' + row + '": { "offset": "0.2" } },' +
'"animation": { "duration": "100", "easing": "out"}' +
'}')
chart.draw(data, s);
}
function selectHandlerOut(e) {
//alert('selectHandlerOut');
var row = e.row;
var s = $.parseJSON('{"is3D": "true", "slices": { "' + row + '": { "offset": "0.0" } } }')
chart.draw(data, s);
}
google.visualization.events.addListener(chart, 'onmouseover', selectHandlerOver);
google.visualization.events.addListener(chart, 'onmouseout', selectHandlerOut);
chart.draw(data, options);
}
I think this is because O override onmouseover event with custom behaviour. Any suggestions?
This is not because you have overridden the mouse over event. This is because you are calling chart.draw() inside it. Draw method cancels out any tooltips which rendered for the previous.
If you want fine-grained control, You are better off using something like jQueryUI to show your tooltips.

How to make google pie chart api background transparent

this is the google code for pie char apt:
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
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]
]);
var options = {backgroundColor: '#676767',
'width':400,
'height':300};
var chart = new google.visualization.PieChart(document.getElementById('priority_customers_report'));
chart.draw(data, options);
}
</script>
Here the backgroundColor: '#676767' gives us the color now I want it to be transparent, how can I do that?
And how to set the text in bottom? As it's not clear in Google Documentation, really tough to understand.
This is related to the Simple Pie Chart of Google
The transparent background can be set with:
var options = {backgroundColor: 'transparent',
'width':400,
'height':300};
You can also set the title there:
var options = {backgroundColor: 'transparent',
'width':400,
'height':300,
'title' : 'My Chart'};
Edit:
To set the right hand items to show at the bottom use:
var options = {backgroundColor: 'transparent',
'width':400,
'height':300,
'title' : 'My Chart'
legend : { position : 'bottom' }
};
The list of possible options are here.
I got the answerbackgroundColor: '#676767' with backgroundColor: {fill: 'transparent'} and it will do the needful.
This will not work on IE as IE does not support Transparency, still we can add color of our choice by writing this code:-
With a bit of help from jQuery:
// check for IE
if ($.browser.msie) {
options2['backgroundColor'] = {fill: <color>};
}
else {
options2['backgroundColor'] = {fill: 'transparent'};
}
Still i am unable to set the position in bottom....
In IE, using jQuery, you can do the following to set the chart's background to transparent:
$('#vis iframe').attr('allowTransparency', 'true');
$('#vis iframe').contents().find('body').css('background', 'transparent');
where #vis is the id of the div where the chart is at.

Google Visualization Animation when chart loads for the first time

I would like to know if I can apply an animation to the charts on the first time it draws?
And not only when a change of data happens?
THanks!
UPDATED ANSWER
Google has updated chart options and added the option to animate the chart on the first time it draws.
So the only thing you have to do is psecify it in the options like that:
var options = {
animation: {
duration: 1500,
startup: true //This is the new option
}
};
So you dont have to load an empty chart on the beggining or to do any other hack.
DEMO
The Chart should be rendered before you can apply your animation which is showing transition from one state to another. You can either change the data or change the chart options to create the transition and its animation.
To be able to show animation on the first time, you can simply create an empty (no data) chart, and then add your data to the chart, to show the data animation.
var options = {
animation:{
duration: 1000,
easing: 'out',
}
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'N');
data.addColumn('number', 'Value');
var chart = new google.visualization.ColumnChart...
chart.draw(data, options);
// Adding data
data.addRow(['V', 200]);
Try something like this http://jsfiddle.net/h7mSQ/163/. The way to do this is to render chart with zero values and then set values as required and draw chart again. Don't forget to set minimal and maximal value for (in this example) vertical axis.
function drawChart() {
var option = {title:"Yearly Coffee Consumption in our company",
width:600, height:400,
animation: {duration: 1000, easing: 'out',},
vAxis: {title: "Cups of coffee", minValue:0, maxValue:500},
hAxis: {title: "Year"}};
var data = new google.visualization.DataTable();
data.addColumn('string', 'N');
data.addColumn('number', 'Value');
data.addRow(['2003', 0]);
data.addRow(['2004', 0]);
data.addRow(['2005', 0]);
// Create and draw the visualization.
var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
chart.draw(data, option);
data.setValue(0, 1, 400);
data.setValue(1, 1, 300);
data.setValue(2, 1, 400);
chart.draw(data, option);
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

Categories

Resources