Google bar chart remove bar when 0 - javascript

I want to be able to remove the spacing that is added when the value is 0 - in the example below there is a max of 4 answers so when the value is 0 removing the spacing will not stretch the graph so much.
// 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', 'Course');
data.addColumn('number', 'Excellent');
data.addColumn('number', 'Adequate');
data.addColumn('number', 'Limited');
data.addColumn('number', 'None');
data.addColumn('number', 'Very Confident');
data.addColumn('number', 'Fairly Confident');
data.addColumn('number', 'Somewhat Confident');
data.addColumn('number', 'Not at all');
data.addRows([
['Knowledge level', 1, 8, 30, 0, 0, 0, 0, 0],
['Assessment skills', 1, 9, 18, 11, 0, 0, 0, 0],
['Planning skills', 2, 7, 20, 10, 0, 0, 0, 0],
['Confidence', 0, 0, 0, 0, 5, 6, 7, 8]
]);
// Set chart options
var options = {
'title': 'Statewide Count across all courses',
'width': 700,
'height': 900
};
// Instantiate and draw our chart, passing in some options.
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
//Wait for the chart to finish drawing before calling the getImageURI() method.
/*google.visualization.events.addListener(chart, 'ready', function(){
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div.innerHTML);
})*/
chart.draw(data, options);
}
Picture here

Related

How to draw google line chart with multiple strings data

I want to display the results of students using a single chart.
There are 4 exam phases in a year and 5 activities in each phase and each activity has grades ranging from A to G.
I'm using google line chart for this purpose.
Code for Generating the graph
[<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Phase');
data.addColumn('string', 'Activity 1');
data.addColumn('string', 'Activity 2');
data.addColumn('string', 'Activity 3');
data.addColumn('string', 'Activity 4');
data.addColumn('string', 'Activity 5');
data.addRows([
['1', 'A','B','C','D','E'],
['2', 'E','D','C','B','A'],
['3', 'A','B','C','D','E'],
['4', 'E','D','C','B','A'],
]);
var options = {
title: 'Student Result',
width: 600,
height: 550,
legend: { position: 'bottom' },
vAxis: { ticks: ['A','B','C','D','E','F','G']}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
</head>
<body>
<div id="line_top_x"></div>
</body>
</html>
Link to the Output of this code
The axis is null. It is not generating the chart as per data.
if you check the data format for a line chart,
only the first column in the data table may be of type 'string',
the rest should be 'number'
in this case, you could convert each grade to a number.
then use object notation to show the grade instead of the number.
using object notation allows you to provide the value (v:) and the formatted value (f:)
{v: 0, f: 'A'}
the formatted value is displayed by default.
next, if you want to customize the vertical axis, by using ticks,
you won't be able to use a material chart --> google.charts.Line
you will need to use a classic chart instead --> google.visualization.LineChart
there are several options that are not supported by material charts, including ticks
see Tracking Issue for Material Chart Feature Parity for more info.
see following working snippet for an example...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var scale = {
'A': 0,
'B': 1,
'C': 2,
'D': 3,
'E': 4,
'F': 5,
'G': 6
};
var grades = [
['1','A','B','C','D','E'],
['2','E','D','C','B','A'],
['3','A','B','C','D','E'],
['4','E','D','C','B','A']
];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Phase');
data.addColumn('number', 'Activity 1');
data.addColumn('number', 'Activity 2');
data.addColumn('number', 'Activity 3');
data.addColumn('number', 'Activity 4');
data.addColumn('number', 'Activity 5');
grades.forEach(function (activities) {
var row = [];
activities.forEach(function (grade, indexGrade) {
if (indexGrade === 0) {
row.push(grade);
} else {
row.push({
v: scale[grade],
f: grade
});
}
});
data.addRow(row);
});
var options = {
title: 'Student Result',
width: 600,
height: 550,
legend: {
position: 'bottom'
},
vAxis: {
ticks: [
{v: 0, f: 'A'},
{v: 1, f: 'B'},
{v: 2, f: 'C'},
{v: 3, f: 'D'},
{v: 4, f: 'E'},
{v: 5, f: 'F'},
{v: 6, f: 'G'}
]
}
};
var chart = new google.visualization.LineChart(document.getElementById('line_top_x'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_top_x"></div>

Google Graphs One value for Y -axis (Stacked columns for Two charts)

Full code
You can use jsfiddle too testing.
google.load('visualization', '1.1', {
'packages': ['bar']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Nescafe Instant');
data.addColumn('number', 'Folgers Instant');
data.addColumn('number', 'Nescafe Beans');
data.addColumn('number', 'Folgers Beans');
data.addRows([
['2001', 500, 1200, 816, 200],
['2002', 163, 231, 539, 594],
['2003', 125, 819, 200, 578],
['2004', 197, 536, 613, 500]
]);
// Set chart options
var options = {
isStacked: true,
width: 800,
height: 600,
chart: {
title: 'Year-by-year coffee consumption',
subtitle: 'This data is not real'
},
series: {
2: {
targetAxisIndex: 1
},
3: {
targetAxisIndex: 1
}
}
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
The Output
The Question
I use Google Visualization to generate above chart.
If you see the above screenshot you can see that Y- axis of above chart has two values in left side and right side. Seems like it happens because graphs use two date range for left side and right side bar.
I wanted to remove right side Y axis or print the same values for both right and left Y axis. I mean all data should be under the Y - axis which is on left side. What can I do to do it?
the options for series.n.targetAxisIndex create the second axis
removing these options will allow all series to default to the first axis
however, in Material bar charts, moving a series to a different axis,
separates the series into multiple stacks, resulting in blue and red bars
removing the options mentioned above will combine all series into one blue stack
in order to keep the stacks separated in two colors,
series.n.targetAxisIndex must be used and dual axis' will be displayed
to keep the two axis' in sync, use option --> vAxis.viewWindow
this will set an identical range for both axis'
vAxis: {
viewWindow: {
min: 0,
max: 1800
}
}
see following working snippet...
google.charts.load('current', {
packages: ['bar']
}).then(drawStuff);
function drawStuff() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Nescafe Instant');
data.addColumn('number', 'Folgers Instant');
data.addColumn('number', 'Nescafe Beans');
data.addColumn('number', 'Folgers Beans');
data.addRows([
['2001', 500, 1200, 816, 200],
['2002', 163, 231, 539, 594],
['2003', 125, 819, 200, 578],
['2004', 197, 536, 613, 500]
]);
var options = {
isStacked: true,
width: 800,
height: 600,
chart: {
title: 'Year-by-year coffee consumption',
subtitle: 'This data is not real'
},
series: {
2: {
targetAxisIndex: 1
},
3: {
targetAxisIndex: 1
}
},
vAxis: {
viewWindow: {
min: 0,
max: 1800
}
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: jsapi should no longer be used to load the charts library,
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. The last update, for security purposes, was with a pre-release of v45. Please use the new gstatic loader.js from now on.
this will only change the load statement, see above snippet...

google.visualization[$attr.googleChart] is not a constructor

I am working on angularjs google charts.
In the example i'm trying to show Line chart and Gantt chart, but facing issue displaying the Gantt chart.
Gantt chart is not shown on the webpage, below is the error shown on the console.
angular.js:5754 TypeError: google.visualization[$attr.googleChart] is not a constructor
Any inputs would be helpful.
js code:
"use strict";
/*We need to manually start angular as we need to
wait for the google charting libs to be ready*/
google.setOnLoadCallback(function () {
angular.bootstrap(document.body, ['my-app']);
});
google.load('visualization', '1', { packages: ['corechart'] });
function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
var myApp = myApp || angular.module("my-app", ["google-chart"]);
myApp.controller("IndexCtrl", function ($scope) {
$scope.data1 = {};
$scope.data1.dataTable = new google.visualization.DataTable();
$scope.data1.dataTable.addColumn('string', 'Task ID');
$scope.data1.dataTable.addColumn('string', 'Task Name');
$scope.data1.dataTable.addColumn('date', 'Start Date');
$scope.data1.dataTable.addColumn('date', 'End Date');
$scope.data1.dataTable.addColumn('number', 'Duration');
$scope.data1.dataTable.addColumn('number', 'Percent Complete');
$scope.data1.dataTable.addColumn('string', 'Dependencies');
$scope.data1.dataTable.addRows([
['Research', 'Find sources',
new Date(2015, 0, 1), new Date(2015, 0, 5), null, 100, null],
['Write', 'Write paper',
null, new Date(2015, 0, 9), daysToMilliseconds(3), 25, 'Research,Outline'],
['Cite', 'Create bibliography',
null, new Date(2015, 0, 7), daysToMilliseconds(1), 20, 'Research'],
['Complete', 'Hand in paper',
null, new Date(2015, 0, 10), daysToMilliseconds(1), 0, 'Cite,Write'],
['Outline', 'Outline paper',
null, new Date(2015, 0, 6), daysToMilliseconds(1), 100, 'Research']
]);
$scope.data3 = {};
$scope.data3.dataTable = new google.visualization.DataTable();
$scope.data3.dataTable.addColumn("string", "Name")
$scope.data3.dataTable.addColumn("number", "Qty")
$scope.data3.dataTable.addRow(["Test", 1]);
$scope.data3.dataTable.addRow(["Test2", 2]);
$scope.data3.dataTable.addRow(["Test3", 3]);
});
You seem to be using an old version of the API. Use loader.js, not jsapi.js
using loader.js, you can load all the libs you needs by specifiying in the packages array. In this case, you need packages: ['corechart', 'gantt']
Here's the demo, updated https://plnkr.co/edit/Fxz9xP7UXqgBs3m0EfSg?p=preview
In index.html
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
and in main.js
google.charts.load('visualization', '1', { packages: ['corechart', 'gantt'] });
google.charts.setOnLoadCallback(function () {
angular.bootstrap(document.body, ['my-app']);
});
Things to note:
It's google.charts namespaced, and not google.load directly
Make sure you call google.charts.load before google.charts.setOnLoadCallback
Make sure you load all the packages you need
You can see old version loading info, & limitations on loading charts in Google documentation here

google charts api - column chart - percentage above vertical bar along with normal values on left side of vaxis

I am using google charts to generate a column chart as shown in this image:
http://postimg.org/image/mt7tzwwob/
Here, data will be like [['a', 1], ['b', 2], ['c', 3]]
Here, I am getting values 1,2,3 on left left side of vaxis which is ok for me.
What I want extra is: The percentages at the top of the vertical bar.
x+2x+3x = 100, means, x=16, 2x=33, 3x=50. So, 16% should be at top of vertical bar with value 1.
How can I get these percentages ?
The ColumnChart's don't support adding labels like a percentage above the columns, but there is a work-around that involves using a ComboChart and a hidden line to add them in. Here's some example code that adds in labels (you can replace the labels with percents in you want):
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([
['Foo', 53, 'Foo text'],
['Bar', 71, 'Bar text'],
['Baz', 36, 'Baz text'],
['Cad', 42, 'Cad text'],
['Qud', 87, 'Qud text'],
['Pif', 64, 'Pif text']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 1, 2]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(view, {
height: 400,
width: 600,
series: {
0: {
type: 'bars'
},
1: {
type: 'line',
color: 'grey',
lineWidth: 0,
pointSize: 0,
visibleInLegend: false
}
},
vAxis: {
maxValue: 100
}
});
}
see it working here: http://jsfiddle.net/asgallant/QjQNX/
This only works well for charts that have a single series of data (as the labels will be misaligned if there is more than one series).

Google Charts API: new google.visualization.Table() - Uncaught TypeError: undefined is not a function

I have copied the Google Code example into a php script however I am getting the error "undefined is not a function"
it is happening specifically on this line:
var table = new
google.visualization.Table(document.getElementById('table_sort_div'));
It appeats that the Table function does not exist???
I have copied the code directly from Googles Code examples so I can't understand what I have done wrong... I'm tending to believe that there is an issue with the example but I'm gonna assume I'd make a mistake before google would?
Code was copied directly from: http://code.google.com/apis/chart/interactive/docs/examples.html#interaction_example
You need to wait for the scripts to load. For example:
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var table = new google.visualization.Table(document.getElementById('table_sort_div'));
}
should work, because the scripts have been loaded. A better table reference here
Also if you want to load multiple packages, you can do that as well like :
google.load('visualization', '1', { packages: ['corechart', 'table'] });
google.charts.load('current', {'packages': ['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time');
data.addRows(5);
data.setCell(0, 0, 'John');
data.setCell(0, 1, 10000, '$10,000');
data.setCell(0, 2, true);
data.setCell(1, 0, 'Mary');
data.setCell(1, 1, 25000, '$25,000');
data.setCell(1, 2, true);
data.setCell(2, 0, 'Steve');
data.setCell(2, 1, 8000, '$8,000');
data.setCell(2, 2, false);
data.setCell(3, 0, 'Ellen');
data.setCell(3, 1, 20000, '$20,000');
data.setCell(3, 2, true);
data.setCell(4, 0, 'Mike');
data.setCell(4, 1, 12000, '$12,000');
data.setCell(4, 2, false);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
google.visualization.events.addListener(table, 'select', function () {
var row = table.getSelection()[0].row;
alert('You selected ' + data.getValue(row, 0));
});
}

Categories

Resources