Multiple Google charts on one web page - google-visualization

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>

Related

Google Chart bars half the correct height in wkhtmltopdf

My Google Chart works perfectly in the browser:
Works perfectly
However, when I try to render this as a PDF using:
wkhtmltopdf --javascript-delay 2000 --print-media-type chart_dummy.html chart_dummy.pdf
the heights of the bars get halved, and the colour code goes missing:
Rendered PDF with bars half height
I take it there must be some wkhtmltopdf option to correct this, but I can't for the life of me identify one.
I'm using Ubuntu 16.04.7 LTS (Xenial Xerus), and wkhtmltopdf 0.12.5 (with patched qt).
My visualization function is
function drawVisualization() {// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'focus name');
data.addColumn('number', 'Exceeded');
data.addColumn('number', 'Achieved');
data.addColumn('number', 'Not Achieved');
data.addColumn('number', 'Regressed');
var width = $($('.container-fluid')[0]).width();
var height = $($('.container-fluid')[0]).height();
var options = {
'width': width,
'height': height,
'chartArea': {top:10},
title: String(),
vAxis: {
title: '% Progress',
minValue: 0,
maxValue: 100,
format: '#\'%\'',
baseline: 0,
},
hAxis: {
title: ''
},
seriesType: 'bars',
series: {
5: {
type: 'line'
}
},
colors: ['#ffe400', '#03ea74', '#ffa000', '#0095ff'],
annotations: {
alwaysOutside: true,
textStyle: {
fontSize: 20,
auraColor: '#eee',
color: '#eee'
}
},
animation: {
duration: 2000,
easing: 'linear',
startup: true
},
legend: 'bottom'
};
reportData = {
"combined": {
"exceeded": "34",
"achieved": "72",
"not_achieved": "14",
"regressed": "8"
}
};
data.addRows([
['All Focus Areas', Number(reportData['combined']['exceeded']), Number(reportData['combined']['achieved']), Number(reportData['combined']['not_achieved']), Number(reportData['combined']['regressed'])]
]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Has anyone a clue how to make the PDF the same as the Browser rendering?

Google Charts vAxis Title not showing

I'm trying to use Google Charts and seem to be running into issues with titles not displaying. Im using a Column Chart and the vAxis title is not displaying. I also started to make a Material Line Chart and I'm running into the same issue.
Here's the Material Line Chart code:
<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','line']});
</script>
</head>
<body>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>
<script language="JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Cycle ID');
data.addColumn('number', '5A Continuous');
data.addColumn('number', '10A Continuous');
data.addColumn('number', '20A Continuous');
data.addColumn('number', '10A Pulse');
data.addColumn('number', '20A Pulse');
data.addRows([
['1', 2548, 2319, 828, 2348, 2192],
['2', 2537, 2306, 829, 2362, 2187],
['3', 2533, 2301, 833, 2347, 2170],
['4', 2530, 2300, 833, 2343, 2156],
['5', 2526, 2297, 837, 2339, 2147],
['6', 2519, 2294, 839, 2340, 2142],
['7', 2510, 2287, 838, 2356, 2146],
['8', 2506, 2276, 839, 2359, 2139],
['9', 2504, 2275, 840, 2346, 2127],
['10', 2500, 2274, 838, 2336, 2119],
]);
var formatter = new google.visualization.NumberFormat({
pattern: '####'
});
formatter.format(data, 1);
formatter.format(data, 2);
formatter.format(data, 3);
formatter.format(data, 4);
formatter.format(data, 5);
// Set chart options
var options = {
chart: {
title: 'LG HG2 Battery Performance Over Cycles',
},
hAxis: {
title: 'Cycle ID',
},
vAxis: {
title: 'Milliamp Hours',
},
'width':550,
'height':400,
lineWidth: 20,
};
// Instantiate and draw the chart.
var chart = new google.charts.Line(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Here's the Column Chart Code:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// create and populate data table,
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable([
['Test', 'Average mAh', { role: 'style' }],
['Manufacturer Specification', 3000, '#804000' ],
['10A Continuous', 2249.970, '#804000' ],
['20A Continuous', 678.349, '#804000'],
['10A Pulsed', 2327.558, '#804000'],
['20A Pulsed', 2080.586, '#804000'],
]);
var formatter = new google.visualization.NumberFormat({
pattern: '####'
});
formatter.format(data, 1);
// Set chart options
var options = {'title':'Tested Average mAh Ratings - LG HG2',
'width':800,
'height':600,
legend: {position: 'none'},
bar: {groupWidth: '90%'},
vAxis: { gridlines: { count: 8 }, minValue: 500}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Any help is greatly appreciated!
Material charts are in beta and you must use a converter function on your options to ensure they work properly. Here is an example:
chart.draw(data, google.charts.Line.convertOptions(options));
For your column chart, you must explicitly set the vaxis.title option like so:
vAxis: { title: 'Average mAh', gridlines: { count: 8 }, minValue: 500}
I'm creating a chart in Google Script and couldn't set the vAxis title either, and similarly couldn't modify some other attributes.
I found success by modifying vAxes[0] instead.
chart.setOption('vAxes', {0: {title: 'title Text'} } )
or if you're using an options variable:
vAxes: { 0: { title: 'Milliamp Hours' } }
Hope this helps anyone with the same issue.

Show data on Chart instead of tooltip

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>

Google charts legend customize

I have two series/columns fileSize and output Target.
Is it possible two display only output Target in the legend and hide fileSize?
you can use the visibleInLegend configuration option
just assign to the series number
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['File', 'fileSize', 'output Target'],
['a', 10, 15],
['b', 12, 18],
['c', 14, 21],
['d', 16, 24]
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, {
legend: {
position: 'bottom'
},
series: {
0: {
visibleInLegend: false
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Drawing visual Lines in Google Charts

I'm writing a Google Chart. It has stacked columns. On top of that I want to draw 2 lines, which indicate min and max allowed value.
The only solution I came up with, was modifying the first example of ComboCharts. My result looks like this:
Which isn't sufficient. The graph is variable, so if there's only 1 Quartal shown, the line will solely be a dot. My Questions are:
Is there a way to draw the line further, so it hits the left and right boundary of the Graph?
Can I draw markup lines into the graph, without pretending it's another datapoint?
You can fiddle with a ComboChart here if you want.
You can't get the lines to go edge-to-edge with a discrete (string-based) x-axis. If you switch to a continuous (number, date, datetime, timeofday) axis, then you can add one row before your real data and one row after that contain the goal lines (and nulls for the other data series):
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Quarter');
data.addColumn('number', 'Value 1');
data.addColumn('number', 'Value 2');
data.addColumn('number', 'Value 3');
data.addColumn('number', 'Goal 1');
data.addColumn('number', 'Goal 2');
data.addRows([
[0, null, null, null, 10, 14],
[1, 5, 4, 7, null, null],
[2, 6, 9, 6, null, null],
[3, 2, 6, 4, null, null],
[4, 3, 6, 4, null, null],
[5, null, null, null, 10, 14]
]);
var chart = new google.visualization.ComboChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 400,
width: 600,
isStacked: true,
legend: {
position: 'top'
},
seriesType: 'bars',
interpolateNulls: true,
series: {
3: {
type: 'line'
},
4: {
type: 'line'
}
},
hAxis: {
format: 'Q#',
ticks: [1, 2, 3, 4],
viewWindow: {
min: 0.5,
max: 4.5
}
},
chartArea: {
left: '10%',
width: '80%'
}
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
See working example: http://jsfiddle.net/asgallant/W67qU/
Here is some explanation of what is going on (edit on Nov 24, 2022 by Jorr.it):
At the top and bottom of the DataTable there are extra rows added with the goals only. With the hAxis.viewWindow option the two new goal dots are just cut off the chart, but resulting in a full line over the whole width of the chart. Finally option "interpolateNulls" needs to be set to connect the two invisible dots "over" the null values in the bar rows.
Maybe a bit late but I faced the same issue. I was trying to set max and min lines into a line chart with a lot of data points in the serie and I wanted to avoid adding new series with a lot of repeated points so I used overlays ( https://developers.google.com/chart/interactive/docs/overlays#javascript2 ).
Here are an example, It's just a draft in which I'm working now but maybe can help:
<html>
<head>
<script
type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"
></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<style>
#container {
position: relative;
width: 900px;
height: 500px;
}
.min-bar {
height: 1px;
background-color: red;
position: absolute;
left: 0;
right: 0;
}
</style>
<script type="text/javascript">
$(function() {
$.get(
"https://firebasestorage.googleapis.com/v0/b/manasav-pricetracker.appspot.com/o/products%2F-L6O-CtBKZAc2NTCFq7Z.data?alt=media&token=60e06bb6-59b7-41a9-8fd0-f82f4ddc75f2",
function(data) {
google.charts.load("current", { packages: ["corechart"] });
google.charts.setOnLoadCallback(drawChart);
var downloadedData = JSON.parse("[" + data);
function drawChart() {
var dataTable = [["Time", "New"]];
let min = Number.MAX_VALUE;
let rowMin;
for (var i in downloadedData) {
var d = downloadedData[i];
if (d.new < min) {
rowMin = i;
min = d.new;
}
dataTable.push([new Date(d.date), d.new]);
}
var data = google.visualization.arrayToDataTable(dataTable);
var options = {
title: "Price evolution",
legend: { position: "bottom" },
trendlines: { 0: {} }
};
var chart = new google.visualization.LineChart(
document.getElementById("curve_chart")
);
function placeMarker(dataTable) {
var cli = this.getChartLayoutInterface();
var chartArea = cli.getChartAreaBoundingBox();
document.querySelector(".min-bar").style.top =
Math.floor(cli.getYLocation(min)) + "px";
document.querySelector(".min-bar").style.left =
Math.floor(cli.getXLocation(dataTable.getValue(0,0))) - 25 + "px";
document.querySelector(".min-bar").style.right =
(document.querySelector("#container").offsetWidth - Math.floor(cli.getXLocation(dataTable.getValue(dataTable.getNumberOfRows()-1,0)))) - 25 + "px";
// document.querySelector(".min-bar").style.top =
// Math.floor(cli.getXLocation(dataTable.getValue(rowMin, 1))) +
// "px";
}
google.visualization.events.addListener(
chart,
"ready",
placeMarker.bind(chart, data)
);
chart.draw(data, options);
}
}
);
});
</script>
</head>
<body>
<div id="container">
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<div class="min-bar"></div>
</div>
</body>
</html>
Jsfiddle demo => https://jsfiddle.net/jRubia/8z7ao1nh/