Google Stacked Bar chart not displayed when data is omitted - javascript

I am trying to implement google charts in my project.
Where I want to display marks of last x tests on bar graph.
But the issue is, user can take any number of subjects for the test like only Math and History.So I only want to show that subjects in a bar chart.
I can not display 0 since "0" might infer that user got 0 marks in that subject. I just want to include those subjects which the user gives test for.
Is this possible in google Chart or any other library ?
Here is the code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Math', 'Science', 'History', 'Geography', { role: 'annotation' } ],
['#1', 10, 24, 20, ''],
['#2', 16, 22, 23, ''],
['#3', 28, 19, 29, '']
]);
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I tried morris.js, but I was unsuccessful.
Any help will be appreciated. Thanks!

Related

How to modify bar width of google chart column?

How I can modify the size of bar width of google chart column? I tried to add 'bar: { groupWidth: "20%" }' but it does nothing to the chart.
I really wanted it to make it thinner.
Here is the code that I want to use from google chart:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 500px;"></div>
</body>
</html>
According to the documentation,
The Material Charts are in beta. The appearance and interactivity are largely final, but many of the options available in Classic Charts are not yet available in them. You can find a list of options that are not yet supported in this issue.
One of these options is the bar.groupWidth, which seems to not have support yet.
In this case, since you are working with a group of bars and there's only one array of information in data:
['2017', 1030, 540, 350]
then that option doesn't seem to work. However, if there were two or more groups, it seemed to render but in a limited way. This said, I was able to find some workarounds, each one with its own positive aspects and drawbacks.
Change from Material Charts to Classical Charts
Here you have to reconstruct the chart's code following the Classical one
Pros: options fully supported
Cons: you will change from Material Charts to Classical Charts
google.charts.load("current", { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Financial status',{ role: "style" }],
["Sales", 1030, "#4285f4"],
["Expenses", 540, "#db4437"],
["Profit", 350, "f4b400"],
]);
var view = new google.visualization.DataView(data);
var options = {
title: "Company Performance",
subtitle: "Sales, Expenses, and Profit: 2017",
width: 600, // chart width
bar: { groupWidth: "45%" }, // width of bars here
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_values" style="width: 900px; height: 300px;"></div>
Separate that only group of bars into single bars
Put that only group bar in different arrays and adapt your labels
Pros: the width will indeed change from 0 to 100% in groupWidth
Cons: looses colored bars
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Type', 'Financial status'],
["Sales", 1030],
["Expenses", 540],
["Profit", 350],
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2017',
},
bar: { groupWidth: '50%' }, // change width here
width: 600, // width of the chart
height: 400 // height of the chart
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(drawChart);
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 300px;">
Use meaningless arrays
Put the array of information in the middle of two other meaningless arrays so
that you center your main data and gives the impression
Pros: still uses the Material Chart design
Cons: stretches the bars, doesn't provide space between bars
google.charts.load('current', { 'packages': ['bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
[' ', 0, 0, 0], // meaningless
['2017', 1030, 540, 350],
[' ', 0, 0, 0] // meaningless
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2017',
},
bar: { groupWidth: '90%' }, // change width of bar here,
width: 600, // width of the chart
height: 400, // height of the chart
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 300px;">

Google charts, i cannot use variables inside javascript

I have a query that get from SQL a list of names and theirs fields (OnTime & Delayed). If i use an echo $datosGrafico in php, it shows the below:
['Agustin', 17, 1 ],
['Andrea', 79, 0 ],
['Carla', 17, 0 ],
['Cecilia', 6, 0 ],
['Denise', 0, 0 ],
['Diego', 3, 0 ],
['Ezequiel', 0, 0 ],
['German', 0, 0 ],
That part is fine. the problem appear once i try to put that variable in the google chart javascript. The script just stop working:
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["bar"]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = google.visualization.arrayToDataTable([
['Analista', 'On Time', 'Delayed'],
//(The variable $datosGrafico SHOULD GO HERE and avoid to insert every name mannualy)
['Agustin', 17, 1],
['Lucas', 6, 2],
]);
var options = {
width: 425,
height: 450,
chart: {
title: 'Spread of SLAs by Analist',
subtitle: 'Amount of Tickets'
},
bars: 'horizontal' // Required for Material Bar Charts.
}
;
var chart = new
google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="dual_x_div" style="width: 300px; height: 450px;"></div>
</body>
Any idea why this is happening?
I hope I understood you correctly. This works:
google.charts.load("current", {packages:["bar"]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff()
{
var data = google.visualization.arrayToDataTable(
[
['Analista', 'On Time', 'Delayed'],
['Agustin', 17, 1 ],
['Andrea', 79, 0 ],
['Carla', 17, 0 ],
['Cecilia', 6, 0 ],
['Denise', 0, 0 ],
['Diego', 3, 0 ],
['Ezequiel', 0, 0 ],
['German', 0, 0 ]
]);
var options =
{
width: 425,
height: 450,
chart:
{
title: 'Spread of SLAs by Analist',
subtitle: 'Amount of Tickets'
},
bars: 'horizontal' // Required for Material Bar Charts.
}
;
var chart = new
google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
}
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dual_x_div" style="width: 300px; height: 450px;"></div>
I've found the solution based on comments here! Thanks!
The php PDO query, return the variable:
$datosGrafico
I added some lines to save that variable result in a php file
$fichero = 'tpl\include\test.php';
$actual = $datosGrafico;
file_put_contents($fichero, $actual);
and then, i've just added the php code to read that file:
dataTable = new google.visualization.DataTable();
var newData = <?php include ('tpl\include\test.php')?>
var numRows = newData.length;
var numCols = newData[0].length;
// in this case the first column is of type 'string'.
dataTable.addColumn('string', newData[0][0]);
// all other columns are of type 'number'.
for (var i = 1; i < numCols; i++)
dataTable.addColumn('number', newData[0][i]);
// now add the rows.
for (var i = 1; i < numRows; i++)
dataTable.addRow(newData[i]);
Hope this help you in the future!

Using wkhtmltopdf to output Google Charts to PDF

We have a Silverstripe project that uses the silverstripe-wkhtmltopdf module to output HTML/CSS/Javascript as PDF.
Simple Javascript like document.write works but I want to output Google Charts using their visualisation API:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.load('visualization', '1', {packages: ['corechart', 'bar']});
</script>
The PDF wasn't showing any of the visualisation output so I used QTBrowser to debug the Javascript - as suggested here: Debugging javascript in wkhtmltopdf
The error I'm getting in QTBrowser is: Error: one or more fonts could not be loaded. from https://www.google.com/uds/api/visualization/1.0/b5ac9efed10eef460d14e653d05f5fbf/webfontloader,dygraph,format+en,default+en,ui+en,bar+en,corechart+en.I.js:737
The HTML looks correct at my end but I don't know the compatibility of QTBrowser, or how it relates to wkhtmltopdf.
Has anyone had any experience/ success with using wkhtmltopdf to output Google Charts?
Here's a good post which explains this topic and shows you how to achieve it
http://codingexplained.com/coding/php/using-google-visualization-with-wkhtmltopdf
<script type="text/javascript">
function init() {
google.load("visualization", "1.1", { packages:["corechart"], callback: 'drawCharts' });
}
function drawCharts() {
drawAccountImpressions('chart-account-impressions');
}
function drawAccountImpressions(containerId) {
var data = google.visualization.arrayToDataTable([
['Day', 'This month', 'Last month'],
['01', 1000, 400],
['05', 800, 700],
['09', 1000, 700],
['13', 1000, 400],
['17', 660, 550],
['21', 660, 500],
['23', 750, 700],
['27', 800, 900]
]);
var options = {
width: 700,
height: 400,
hAxis: { title: 'Day', titleTextStyle: { color: '#333' } },
vAxis: { minValue: 0 },
curveType: 'function',
chartArea: {
top: 30,
left: 50,
height: '70%',
width: '100%'
},
legend: 'bottom'
};
var chart = new google.visualization.LineChart(document.getElementById(containerId));
chart.draw(data, options);
}
</script>
</head>
<body onload="init()">
<div id="chart-account-impressions"></div>
</body>

Why this Javascript Chart won't work twice?

I've got some charts of http://canvasjs.com/javascript-charts/ and they are just wonderful! I used one of them and it worked perfectly :
<script type="text/javascript">
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['ip', 'quantity'],
#foreach($ipsWithBytesDates as $item)
['{{$item['ip']}}', {{$item['counts']}}],
#endforeach
]);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
<div id="piechart_3d" style="width: 700px; height: 350px;"></div>
Now i need a second chart - I've already got it from the website and copy & paste it in my code.. but this haven't worked like I want.. the second chart works but overwrites the whole first chart.
The first chart is a column chart and is at the top of my page.. the second chart should be at the bottom.. but it isn't, it every time just overwrites my first chart -- could anybody tell me why? I think it's because of the "window.onload" at the beginning of both chart.. but I haven't really worked with javascript.
second chart:
<script type="text/javascript">
window.onload = function () {
var secchart = new CanvasJS.Chart("chartContainer2",
{
title:{
text: "U.S Smartphone OS Market Share, Q3 2012",
fontFamily: "Impact",
fontWeight: "normal"
},
legend:{
verticalAlign: "bottom",
horizontalAlign: "center"
},
data: [
{
//startAngle: 45,
indexLabelFontSize: 20,
indexLabelFontFamily: "Garamond",
indexLabelFontColor: "darkgrey",
indexLabelLineColor: "darkgrey",
indexLabelPlacement: "outside",
type: "doughnut",
showInLegend: true,
dataPoints: [
{ y: 53.37, legendText:"Android 53%", indexLabel: "Android 53%" },
{ y: 35.0, legendText:"iOS 35%", indexLabel: "Apple iOS 35%" },
{ y: 7, legendText:"Blackberry 7%", indexLabel: "Blackberry 7%" },
{ y: 2, legendText:"Windows 2%", indexLabel: "Windows Phone 2%" },
{ y: 5, legendText:"Others 5%", indexLabel: "Others 5%" }
]
}
]
});
secchart.render();
}
</script>
<script type="text/javascript"></script>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
source code from the chartlibary:
You need to have separate containers for each chart. Each snippet you've pasted is using var chart = new CanvasJS.Chart("chartContainer",
Try setting the 2nd chart to use a different element on your page.
<div id="chartContainer1" style="height: 300px; width: 100%;"></div>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
var chart = new CanvasJS.Chart("chartContainer1", ...
var chart = new CanvasJS.Chart("chartContainer2", ...
Looks like both of these charts are being rendered in an element called "chartContainer". In both code snippets there is a div at the bottom with this name. You should change the name of this div for at least one of the charts.

Google Charts bar chart: How to manually change the colour of every bar? (single series)

I have written a simple bar chart with Google Charts, one series, it works fine, all bars are blue:
Now I would like to manually set the colour of the every single bar (actually a green-to-red transition proportional to the value, to make it easier to understand what is good/bad).
How can I do this?
I have tried setting colors in options as described here but for some reason it does not work in my code below.
chco seems to be what I need, but it is an URL parameter... how to elegantly integrate it in JavaScript code?
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Product', 'Score'],
['NemakiWare', 288],
['Nuxeo', 240],
['FileNet', 220],
['SharePoint', 98]
]);
var options = {
colors: ['green','blue','pink','red'],
legend: 'none',
hAxis: {
textPosition: 'none',
minValue: 0,
gridlines: {
color: 'transparent'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
There are different ways to do this but you can use the style role.
Source:
https://developers.google.com/chart/interactive/docs/gallery/columnchart#Colors
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Product', 'Score', { role: 'style' }],
['NemakiWare', 288, 'green'],
['Nuxeo', 240, 'blue'],
['FileNet', 220, 'pink'],
['SharePoint', 98, 'red']
]);
var options = {
legend: 'none',
hAxis: {
textPosition: 'none',
minValue: 0,
gridlines: {
color: 'transparent'
}
}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.clearChart();
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

Categories