merge total of Stacked Bar Chart - google-visualization

I have two unsigned integers per bar: X and Y.
X is always less than Y because it is a subset of it.
I want to combine these two values into a single bar. However, the Stacking Bar Chart adds up the values instead of "overlapping" them.
This is what isStacked: true results in:
XXXYYYYY
(3x + 5y, Axis goes up to 8)
And here is what my goal is:
XXXYY
(3x within 5y, Axis goes up to 5)
How can I "merge" the values into one bar that is based on Y only and thus doesn't impact the axis' maximum value?

the data will need to be adjusted, setting chart options won't get it.
you could create a view, add a calculated column, and exclude the original Y...
google.charts.load('current', {
packages: ['corechart'],
callback: drawChart
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'X', 'Y'],
['2016', 3, 5]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (data, row) {
return {
v: data.getValue(row, 2) - data.getValue(row, 1),
f: data.getValue(row, 2).toString()
};
},
type: 'number',
label: 'Y'
}]);
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(view, {isStacked: true});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

How do I move the x axis like a window in google chart while x increases

I would like to draw a chart to my html, the chart I am using is google chart. However, while my x value is increasing, the chart is getting bigger. But I just want a fixed size window which increase both minimum x value and maximum x value. Like sliding window.
The attachment below is my code. This is the js code which updates the gets the value and updates the chart
// load google charts library
google.load("visualization", "1", {packages:["corechart"]});
// for rest, walk, fast_walk data
var data, options, chart;
var xMin = 0;
var xMax = 10;
var i = 0;
/* initialize chart1 - rest, walk, fast_walk data */
function drawChart(data, options) {
var chart = new
google.visualization.LineChart(document.getElementById('data-container'));
chart.draw(data, options);
return(chart);
}
/* update the chart1 - rest, walk, fast_walk data */
function updateChart(percentage) {
i = (i + 1);
data.addRow([
""+i,
percentage
]);
if(xMax >= 9) {
xMin + 1;
}
xMax + 1;
chart.draw(data, options);
}
$(function() {
data = google.visualization.arrayToDataTable([
['Time', 'percentage'],
['0', 0],
]);
options = {
title: 'Energy data',
"curveType": "function",
vAxis: {
min: xMin,
max: xMax
}
};
chart = drawChart(data, options);
});
/* reset charts */
function reset(){
i = 0;
data = google.visualization.arrayToDataTable([
['Time', 'percentage'],
['0', 0],
]);
options = {
title: 'Energy data',
"curveType": "function",
hAxis: {
viewWindow: {
min: 0,
max: 10
}
}
};
chart = drawChart(data, options);
}
I am wondering if it can be designed into a sliding window, so that the x value doesn't stick with the minimum value 0. instead if we want to see the earliest value, we can just scroll left.
According to the documentation at [https://developers.google.com/chart/interactive/docs/gallery/linechart]
/* copied from site*/
var options = {
chart: {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)'
},
width: 900, //<--- set fixed width like so
height: 500
};
To get a scrollable div,you can wrap your chart inside another div
<div class='h-scrollable' > <!---- chart code here ----> </div>
and for css
.h-scrollable {
width: 100%;
overflow: hidden; // only if you don't want y axis to be scrollable
overflow-x: auto;
}
Now, for the chart give a width depending on the number of x values you have. You could do a mathematical computation by taking the width of the h-scrollbale div in javascript and dividing it by number of x-points you want in a window and then multiplying it with total x values you have and setting it as chart width.
Update:
inititally get the width of h-scrollable as let viewWidth = document.querySelector(".h-scrollable").offsetWidth
[refer : How to find the width of a div using raw JavaScript?
Then if you want to show 10 x values in a view, divide viewWidth by 10 to get one xWidth. Now you can re-render the chart each time by setting width as no.of X values * xWidth so that it scrolls accordingly
Upon each update, you can just remove the first raw.

google chart api material date month

I have a google bar chart with multiple series and a date hAxis.
My problem is that i want to show months only, but i get the label multiple times.
Here's an example
google.charts.load('current', {'packages': ['bar'], 'language': 'de'});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var chart;
var chartDiv = document.getElementById('test');
var data = new google.visualization.DataTable('{"cols":[{"type":"date","pattern":""},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"}],"rows":[{"c":[{"v":"Date(2016,2,1)"},{"v":2030,"f":"2030 km"},{"v":2098,"f":"2098 km"},{"v":1352,"f":"1352 km"},{"v":4412,"f":"4412 km"},{"v":132,"f":"132 km"},{"v":2435,"f":"2435 km"},{"v":3952,"f":"3952 km"}]},{"c":[{"v":"Date(2016,3,1)"},{"v":3177,"f":"3177 km"},{"v":2901,"f":"2901 km"},{"v":2491,"f":"2491 km"},{"v":1480,"f":"1480 km"},{"v":2272,"f":"2272 km"},{"v":400,"f":"400 km"},{"v":1096,"f":"1096 km"}]}]}');
var options = {
legend: { position: 'none' },
hAxis: {
type: 'category',
format: 'MMMM'
}
};
chart = new google.charts.Bar(chartDiv);
chart.draw(data, google.charts.Bar.convertOptions(options));
}
https://jsfiddle.net/1Lusd06n/3/
If i shrink the width of the fiddle, the month names are grouped and displayed once but this does not happen if there is more space.

"Table has no rows" Error in Google Charts Histogram

I am working with Google Histogram chart. It working fine with some data sets but not for other data sets. And it raise an error "Table has no rows" even my input is correct.
Here i am reading a csv file column wise and pass to visualization page.
for eg: I am reading 2 csv column here and passing to visualization page. Here my input to Google histogram is
var inputdata1 = [["val","d"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","1"],["val","2"]];
and this working fine and gives histogram for me.
while I am passing other 2 columns.Here my input to Google histogram is
var inputdata2 = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
while executing this, it raise an error that "Table has no rows" . Please check my fiddle.
Any help would be greatly appreciated.
Thank you in Advance.
In fact neither inputdata1 nor inputdata2 contain JSON data that are supported by histogram chart.
According to the documentation the following formats are supported:
Data Format
There are two ways to populate a histogram datatable. When there's
only one series:
var data = google.visualization.arrayToDataTable([
['Name', 'Number'],
['Name 1', number1],
['Name 2', number2],
['Name 3', number3],
...
]);
...and when there are multiple series:
var data = google.visualization.arrayToDataTable([
['Series Name 1', 'Series Name 2', 'Series Name 3', ...],
[series1_number1, series2_number1, series3_number1, ...],
[series1_number2, series2_number2, series3_number2, ...],
[series1_number3, series2_number3, series3_number3, ...],
...
]);
Having said that you might want to convert the second column into number format:
var inputJson = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
var chartJson = inputJson.map(function(item,i){
if(i == 0)
return item;
else {
return [item[0],parseInt(item[1])];
}
});
var data = google.visualization.arrayToDataTable(chartJson);
Once the data is converted the chart will be rendered properly.
Working example
google.load('visualization', '1.1', {
'packages': ['corechart']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var inputJson = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
var chartJson = inputJson.map(function(item,i){
if(i == 0)
return item;
else {
return [item[0],parseInt(item[1])];
}
});
var data = google.visualization.arrayToDataTable(chartJson);
//The below input data works fine.
//var data = google.visualization.arrayToDataTable([["val","d"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","1"],["val","2"]]);
// Set chart options
var options = {
width: 400,
height: 300,
histogram: {
bucketSize: 0.1
}
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Histogram(document.getElementById('chart_div'));
chart.draw(data, options);
};
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="chart.js"></script>
<div id="chart_div"></div>

google chart discrete axis show line?

I'm using google charts with discrete values and can't seem to get the vAxis line to be drawn (in black).
It appears when graphic in Continuous values but I don't want the chart to be spaced out that way.
here are the 2 types of graphs.
http://jsfiddle.net/cFHJY/
google.load("visualization", "1", {packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var discreteData = new google.visualization.DataTable();
discreteData.addColumn('string', 'Number');
discreteData.addColumn('number', 'Value');
discreteData.addRows([
['1.492', 10],
['30.701', 17],
['127.469', 6],
['749.382', 11]
]);
var discreteChart = new google.visualization.ColumnChart(document.getElementById('discrete_chart_div'));
discreteChart.draw(discreteData, {
title: 'Discrete Axis Line Chart'
});
var continuousData = new google.visualization.DataTable();
continuousData.addColumn('number', 'Number');
continuousData.addColumn('number', 'Value');
continuousData.addRows([
[1.492, 10],
[30.701, 17],
[127.469, 6],
[749.382, 11]
]);
var continuousChart = new google.visualization.ColumnChart(document.getElementById('continuous_chart_div'));
continuousChart.draw(continuousData, {
title: 'Continuous Axis Line Chart'
});
}
How do I get the vAxis line to be drawn?
The "vAxis line" is actually the hAxis baseline, which is only available to continuous axes. With a bit of hackery, you can put your data on a continuous axis while appearing to keep its discrete nature. Use a DataView to convert your data to a "number" type (using the row index for the value and the string value as the formatted value) and build the hAxis.ticks option from the value/formatted value pairs in the view:
function drawChart() {
var discreteData = new google.visualization.DataTable();
discreteData.addColumn('string', 'Number');
discreteData.addColumn('number', 'Value');
discreteData.addRows([
['1.492', 10],
['30.701', 17],
['127.469', 6],
['749.382', 11]
]);
var view = new google.visualization.DataView(discreteData);
view.setColumns([{
type: 'number',
label: discreteData.getColumnLabel(0),
calc: function (dt, row) {
return {v: row + 1, f: dt.getFormattedValue(row, 0)};
}
}, 1]);
var ticks = [];
for (var i = 0; i < view.getNumberOfRows(); i++) {
ticks.push({v: view.getValue(i, 0), f: view.getFormattedValue(i, 0)});
}
var range = view.getColumnRange(0);
var offset = 0.5; // change this to move the left/right margins of the chart
var discreteChart = new google.visualization.ColumnChart(document.getElementById('discrete_chart_div'));
discreteChart.draw(view, {
title: 'Discrete Axis Line Chart',
hAxis: {
ticks: ticks,
viewWindow: {
min: range.min - offset,
max: range.max + offset
},
// set gridlines.color to "transparent" to hide the vertical gridlines
/*
gridlines: {
color: 'transparent'
}
*/
}
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
Ex: http://jsfiddle.net/asgallant/h4Kfd/

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}