What I want to do
Show multiple Barcharts on one Page
What I already did
The Barcharts have prevously been Linecharts. As Linecharts I could show two Charts on the same page without a problem. I used two seperate drawChart()-functions for them. I then converted the charts to Barcharts (material design). Now it only shows one chart. I already searched for an answer and found this: How to add two Google charts on the one page? I follow this and it still doesn't work.
My Code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {
packages: ["Bar"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = new google.visualization.DataTable();
data1.addColumn("string", "Key1");
data1.addColumn("number", "Value1");
data1.addRows([
['2015.01', 65.5],
['2015.02', 52.6],
['2015.03', 45.5],
['2015.04', 40.7],
['2015.05', 68.7],
['2015.06', 56.4],
['2015.07', 38.4],
['2015.08', 45.2],
['2015.09', 45.2],
['2015.10', 4.8]
]);
var data2 = new google.visualization.DataTable();
data2.addColumn("string", "Key2");
data2.addColumn("number", "Value2");
data2.addRows([
['2015.01', 300.08],
['2015.02', 455.08],
['2015.03', 454.62],
['2015.04', 362.93],
['2015.05', 527.12],
['2015.06', 588.28],
['2015.07', 409.93],
['2015.08', 432.08],
['2015.09', 462.33],
['2015.10', 32.38]
]);
var options = {};
var chart1 = new google.charts.Bar(document.getElementById("chart_div1"));
chart1.draw(data1, options);
var chart2 = new google.charts.Bar(document.getElementById("chart_div2"));
chart2.draw(data2, options);
}
</script>
<div id="chart_div1"></div>
<div id="chart_div2"></div>
Best viewed here: https://jsfiddle.net/yrzf3v97/
The Problem
It only shows one chart. Most of the tme its the first but in sometimes its the second one. By using the alert()-function it can confirm that the code runs until the end.
It seems this behavior is related with
draw
function. In particular, the second chart is not rendered since chart SVG is not getting generated afterdraw
function is invoked for the second time.According to the documentation:
For rendering multiple charts on the page you could consider the following approach: render the next chart once the previous one is rendered, for example:
Complete example
For anyone who runs into this problem in 2016, you may have code like I did which referred to an older version of Google Charts. Update your references to follow the latest guidelines at https://developers.google.com/chart. In my case, the following line-for-line changes fixed the issue:
old:
new: