When my chart animates to display new data, the labels on the columns disappear and are not rendered again. All the the data is being imported correctly and displayed on the columns. The label data is only displayed on the initial render of the chart.
The success handler returns 'values', an array of three numbers, for example: [10, 8, 2] and is working correctly.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="genderChart" style="overflow: hidden"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(initChart);
var chart;
var options = {
legend: {position: "none"},
chartArea: {width:'100%'},
animation: {duration: 1000, easing: 'out'}
};
function initChart() {
chart = new google.visualization.ColumnChart(document.getElementById('genderChart'));
drawGenderChart();
}
function drawGenderChart() {
google.script.run.withSuccessHandler(function (values){
genderData = values;
}).getGenderData();
label00 = JSON.stringify(genderData[0]);
label01 = JSON.stringify(genderData[1]);
label02 = JSON.stringify(genderData[2]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'Students');
data.addColumn({role: 'style'});
data.addColumn({role: 'annotation'});
data.addRows([
['Male', genderData[0], '#9fc5e8', label00],
['Female', genderData[1], '#d5a6bd', label01],
['Non-binary', genderData[2], '#b7b7b7', label02]
]);
chart.draw(data, options);
}
setInterval(drawGenderChart, 1000);
</script>
</body>
</html>
Apps Script:
function getGenderData() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Console");
var range = sheet.getRange("A3:C4");
var values = range.getValues();
return values.flat();
}
google.script.run runs asynchronously, so you need to wait for it to finish,
before drawing the chart.
to accomplish, simply place the rest of the code within the success handler...
google.script.run.withSuccessHandler(function (values){
genderData = values;
label00 = JSON.stringify(genderData[0]);
label01 = JSON.stringify(genderData[1]);
label02 = JSON.stringify(genderData[2]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'Students');
data.addColumn({role: 'style'});
data.addColumn({role: 'annotation'});
data.addRows([
['Male', genderData[0], '#9fc5e8', label00],
['Female', genderData[1], '#d5a6bd', label01],
['Non-binary', genderData[2], '#b7b7b7', label02]
]);
chart.draw(data, options);
}).getGenderData();
Related
I need to put a json from eloquent in a google chart but I can't convert the result from eloquent to a correct dataTable
//activos represents result from eloquent
var activos = [
{"descripcion":"peri\u00f3dico","riesgo":"5"},
{"descripcion":"autom\u00e1ticas ","riesgo":"2"},
{"descripcion":" \tAusencia","riesgo":"2"},
{"descripcion":" \tAusencia de alto riesgo","riesgo":"4"},
{"descripcion":"negocio","riesgo":"3"}
];
google.charts.load('current', {
'packages': ['corechart']
});
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Descripcion');
data.addColumn('number', 'Cantidad');
data.addRows(activos);
// Set chart options
var options = {
'title': 'Reporte de Activos',
'width': 400,
'height': 300,
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
the chart doen't apear
Instead of:
data.addRows(activos);
Use something like this:
for(let j in activos){
data.addRows([activos[j].descripcion, activos[j].riesgo]);
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//www.gstatic.com/charts/loader.js'></script>
<script>
var activos = [
{"descripcion":"peri\u00f3dico","riesgo":"5"},
{"descripcion":"autom\u00e1ticas ","riesgo":"2"},
{"descripcion":" \tAusencia","riesgo":"2"},
{"descripcion":" \tAusencia de alto riesgo","riesgo":"4"},
{"descripcion":"negocio","riesgo":"3"}
];
const loadchart=function(){
let dataTbl = new google.visualization.DataTable();
dataTbl.addColumn( 'string', 'Descripcion' );
dataTbl.addColumn( 'number', 'Cantidad' );
activos.forEach( obj=>{
let data=[ obj['descripcion'], parseInt( obj['riesgo'] ) ];
dataTbl.addRows( [ data ] );
});
let chart = new google.visualization.PieChart( document.getElementById('chart') );
chart.draw( dataTbl,{ width:400, height:300, title:'Reporte de Activos' } );
}
google.charts.load( 'current', {'packages':['corechart'] } );
google.charts.setOnLoadCallback( loadchart );
</script>
</head>
<body>
<div id='chart'></div>
</body>
</html>
I am passing data to my flask html template. In the html, there is a Javascript, where I need iterate value. data looks Like,
data[0] = 2, data[1] = 3, data[3] = 5, data[2] = .36 so on
index.html :-
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
{% for i in data %}
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBackgroundColor);
function drawBackgroundColor() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
data.addRows([
[{{i[2]}}, {{i[6]}}]
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Popularity'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
{% endfor %}
</html>
I want to iterate the value here,
data.addRows([
[{{i[2]}}, {{i[6]}}]
]);
It should be like,
data.addRows([
[0,0], [0,1], [1,0], [1,1]
]);
But, it is iterating the whole script.
The entire script is inside of the for loop, so the templating engine will duplicate the script as many times as there are entries in data.
I want to load google chart library and use it from only one script tag.
Here is example of my code. When I loaded google API with separate script
everything working properly. But I want to use just one script if it is
possible.
<html>
<head>
<title>one script tag test</title>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
<script type="text/javascript">
// Here I'm creating a script object and
// load jsapi
var scr = document.createElement("script");
scr.setAttribute("src","https://www.google.com/jsapi");
document.head.appendChild(scr);
// here i wait until
// google object appears.
(function waitForGoogleLoad() {
if(typeof google == 'undefined') {
setTimeout(waitForGoogleLoad, 0);
} else {
processChart();
}
})();
function processChart() {
// 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'));
chart.draw(data, options);
}
}
</script>
</body>
</html>
I would be very grateful for any ideas and recommendations.
Best regards.
The easiest way to handle this is to use the autoloader syntax in the script tag. That allows you to avoid any issues with waiting for the script to load and calling the google loader from inside another function:
var scr = document.createElement("script");
scr.setAttribute("src",'https://www.google.com/jsapi?autoload={"modules":[{"name":"visualization","version":"1","packages":["corechart"],"callback":"drawChart"}]}');
document.head.appendChild(scr);
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'));
chart.draw(data, options);
}
See a working example here: http://jsfiddle.net/asgallant/G9PKE/
I took this code from their official site.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['motionchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Fruit');
data.addColumn('date', 'Date');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addColumn('string', 'Location');
data.addRows([
['Apples', new Date (1988,0,1), 1000, 300, 'East'],
['Oranges', new Date (1988,0,1), 1150, 200, 'West'],
['Bananas', new Date (1988,0,1), 300, 250, 'West'],
['Apples', new Date (1989,6,1), 1200, 400, 'East'],
['Oranges', new Date (1989,6,1), 750, 150, 'West'],
['Bananas', new Date (1989,6,1), 788, 617, 'West']
]);
var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
chart.draw(data, {width: 600, height:300});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 600px; height: 300px;"></div>
</body>
</html>
When i run the code, nothing shows up. What possibly can be the problem? I'm using Chrome.
I could fix this.
The problem was I had these lines in the header:
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization', 'version':'1','packages':['timeline']}]}"></script>
And then the java script executes google.load('visualization', '1', {'packages':['motionchart']});
It seems this "double load" is the problem
I removed the first line and it worked
I am trying to create a linked view in Google Chart. What a linked view is selecting a part of visualization, let's say in a pie chart, and the same is selected (or highlighted) in the linked view, which let's say is the bar chart. I am a novice at Google Charts and I don't know how to use JavaScript too. I picked up the code from the Google Documentation and did some modifications in it. But it does not seem to work. The code is as follows:
<!DOCTYPE HTML>
<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);
google.setOnLoadCallback(drawChart2);
// 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'));
var chart2 = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
function drawChart2() {
// 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.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
You need to use "select" event handlers to link the two charts together, like this:
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 chart1 = new google.visualization.PieChart(document.getElementById('chart_div_1'));
var chart2 = new google.visualization.BarChart(document.getElementById('chart_div_2'));
// set up event handlers
// when a user clicks on the PieChart, set the selection on the BarChart
google.visualization.events.addListener(chart1, 'select', function () {
var selection = chart1.getSelection();
for (var i = 0; i < selection.length; i++) {
// add in column information to specify selection in BarChart
selection[i].column = 1;
}
chart2.setSelection(selection);
});
// when a user clicks on the BarChart, set the selection on the PieChart
google.visualization.events.addListener(chart2, 'select', function () {
var selection = chart2.getSelection();
for (var i = 0; i < selection.length; i++) {
// remove column information for selection in PieChart
selection[i].column = null;
}
chart1.setSelection(selection);
});
chart1.draw(data, options);
chart2.draw(data, options);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
You need two divs in your HTML, one for each chart:
<div id="chart_div_1"></div>
<div id="chart_div_2"></div>
See working example here: http://jsfiddle.net/asgallant/S78sB/