stacked column chart for two data sets - Google Charts - charts

I'm generating some Google Charts and I'm stuck here. Google allows you to have your columns stacked. But it's either limited or I can't configure it to work. Taken from Google, here is an example showing number of cups of coffee produced in each year for two countries:
Say I have another data set for the same two countries, but this time I have instant coffee instead of ground. Example:
What I'd like to do is to stack these two datasets on top of each other. So each column would be a single country, but two divisions: bean and instant coffee.
I was thinking if there was a way of formatting the data table in the following way:
['Year', 'Austria', 'Austria (instant)', 'Bulgaria', 'Bulgaria (instant')],
['2003', 1736060, 10051, 250361, 68564],
['2004', 1338156, 65161, 786849, 1854654],
['2005', 1276579, 65451, 120514, 654654]
to generate something like
Your help is appreciated.

I just ran into this same issue today and followed your submission link. It seems that just recently someone replied with this:
"This is actually possible with the new Material Bar chart (albeit in
a somewhat roundabout way). In the new chart, if you make a chart
stacked, but place some series on a different axis, that creates a
separate stack for those series. Unfortunately, there is currently no
way to completely hide an axis yet, and you will have to explicitly
set the view window. Eventually we will introduce options to hide axes
and to align view windows, but this will have to do for now."
This fiddle seemed to help me solve this problem: http://jsfiddle.net/p7o0pjgg/
Here's the code:
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', 321, 621, 816, 319],
['2002', 163, 231, 539, 594],
['2003', 125, 819, 123, 578],
['2004', 197, 536, 613, 298]
]);
// Set chart options
var options = {
isStacked: true,
width: 800,
height: 600,
chart: {
title: 'Year-by-year coffee consumption',
subtitle: 'This data is not real'
},
vAxis: {
viewWindow: {
min: 0,
max: 1000
}
},
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));
};

You can do it using a stacked column chart, where all data series of one group (e.g. ground coffee) is on the left axis, and all data series of the other group on the right axis (instant coffee).
data and stacked column chart set-up
series of group 2 moved to right axis

The Visualization API does not support creating multiple column stacks per row of data. You can make a feature request to add support for this if you want.

The answer by Dan Hogan worked for me. However, the JSFiddle example didn't seem to work (not sure, why.) Here is a version that works for me.
google.charts.load('current', {'packages': ['bar']});
google.charts.setOnLoadCallback(function() {
$('.service-usage-graph').each(function() {
var table = new google.visualization.DataTable();
table.addColumn('string', 'Date');
table.addColumn('number', 'UL Peak');
table.addColumn('number', 'UL Off-peak');
table.addColumn('number', 'DL Peak');
table.addColumn('number', 'DL Off-peak');
table.addRow(['2001-01-01', 1, 2, 3, 4]);
table.addRow(['2001-01-03', 3, 2, 4, 2]);
table.addRow(['2001-01-04', 2, 2, 4, 2]);
table.addRow(['2001-01-05', 0, 1, 4, 5]);
table.addRow(['2001-01-06', 9, 2, 6, 8]);
table.addRow(['2001-01-07', 2, 2, 7, 3]);
var chart = new google.charts.Bar(this);
var options = google.charts.Bar.convertOptions({
isStacked: true,
series: {
2: { targetAxisIndex: 1 },
3: { targetAxisIndex: 1 }
},
vAxis: {
viewWindow: {
max: 15,
}
}
});
chart.draw(table, options);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="service-usage-graph"></div>

Related

Google Bar charts - ToolTips not showing

I have created a bar chart using google charts, this is a CORE Chart
I have tried getting the bar chart to change colours and adding an additional tooltip information to it, so that the tooltip shows a bit more information
I have gone through the google documentation and i cant see what i am doing wrong
For easy reading this is the output of my code on the source
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var exams = [["Date", "Score",({type: 'string', role: 'tooltip'})], ["18 Oct", 39,"TEST"], ["26 Oct", 20,"TEST"], ["26 Oct", 0,"TEST"], ["27 Oct", 0,"TEST"], ["27 Oct", 0,"TEST"]];
if(exams.length > 1){
var data = google.visualization.arrayToDataTable(exams);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
title: "Results",
width: 1170,
height: 700,
bar: {groupWidth: "95%"},
legend: { position: "none" }
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
else{
$("#columnchart_values").html('No Data found to show graph');
}
}
This is the google documentation i have been following, its slightly different
to mine as i am getting my data from a database, but it should give the same output.
I have gone through many examples and i am replicating them as close as possible and just not having any luck
https://developers.google.com/chart/interactive/docs/customizing_tooltip_content
I also have the exact same problem with color, i cant get colors on bar charts to change both having the same problem that it just doesn't do anything
Am i missing something??
the tooltip column is not being included in the data view.
view.setColumns([0, 1]);
to add the tooltip...
view.setColumns([0, 1, 2]);

Google Charts colors for Column Chart

I have Pie and Column charts from the same source data.
I want colors in bar chart to have the corrsponding colors like in Pie chart. These are default Google Charts colors (in order). So first column should be blue, second red, third yellow and fourth green. How to achieve this?
in a column chart, values in the same series are the same color by default
series are defined by columns, to have different colors by default,
place each value in a separate column
however, this presents a problem
if you structure the data as follows, then you lose the x-axis labels
you only have one label for all columns
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2', 'y3'],
['Razina0', 898, 37319, 8980, 35400]
]);
if you try the next approach, then the columns will not be spaced properly
there will be gaps for the null values
var data = google.visualization.arrayToDataTable([
['x', 'y0', 'y1', 'y2', 'y3'],
['Razina0', 898, null, null, null],
['Razina1', null, 37319, null, null],
['Razina2', null, null, 8980, null],
['Razina3', null, null, null, 35400],
]);
the best option is to use a style column
this will allow you to keep the current data structure
and provide different colors for each column
the only drawback is you have to provide the color
so you lose the default colors
as such, recommend drawing the pie chart first
then use the colors assigned to each slice
when the pie chart's 'ready' event fires
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['x', 'y0'],
['Razina0', 898],
['Razina1', 37319],
['Razina2', 8980],
['Razina3', 35400]
]);
var chartPie = new google.visualization.PieChart(document.getElementById('chart_pie'));
var chartColumn = new google.visualization.ColumnChart(document.getElementById('chart_column'));
google.visualization.events.addListener(chartPie, 'ready', function () {
var colIndex = data.addColumn({type: 'string', role: 'style'});
$.each($('#chart_pie path'), function (rowIndex) {
data.setValue(rowIndex, colIndex, $(this).attr('fill'));
});
chartColumn.draw(data, {
legend: {
position: 'none'
}
});
});
chartPie.draw(data, {
height: 240
});
}
div {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_pie"></div>
<div id="chart_column"></div>

Google Charts Legend labels cut off

The legend labels for my pie chart are being cut off when the label is too long. I have already tried to setting width to '100%' but my legend is way big to counter that. Is there a way to discretely define the pie chart size and the legend size? Could someone please share a working example of the same.
Link for JS Fiddle: https://jsfiddle.net/2nzzLe18
The container div dimensions and the legend label font size are part of my requirement.
Also below is the code,
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['info regarding task Work', 11],
['info regarding task Eat', 2],
['info regarding task Commute', 2],
['info regarding task Watch TV', 2],
['info regarding task Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
chartArea: {left: -100, width: '100%'},
legend: {textStyle: {fontSize: 15}},
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
Thanks,
Farhan
it can be cumbersome to properly size a pie chart,
but it boils down to adjusting the size of the overall chart div,
and the size of the chartArea, where the pie is drawn (separate from the legend)
it can be tricky because it doesn't always respond how you think it should,
but I was able to get the entire legend to display
see the following working snippet,
moved the overall size from the style attribute on the div
to the options for the chart, then adjusted the chartArea
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['info regarding task Work', 11],
['info regarding task Eat', 2],
['info regarding task Commute', 2],
['info regarding task Watch TV', 2],
['info regarding task Sleep', 7]
]);
var options = {
backgroundColor: 'cyan',
title: 'My Daily Activities',
chartArea: {
left: 0,
height: 250,
width: 600
},
height: 300,
width: 600,
legend: {
maxLines: 1,
textStyle: {
fontSize: 15
}
},
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>

How to add vertical bands to a combo chart (line + bar) using google developer charts

I have to create a line chart, which has vertical bands in the background, and a vertical line at a specified position.Following is a sample chart image.
Sample chart
I tried to create a combo chart with line and bar as my series, to get the blue line and red vertical line. But i am unable to figure out how to get the vertical bands. Histogram is not supported by the combo chart. There is no option to create bar charts with variable width of each bar as well. Following is what i am able to create till now:
chart created so far
Following is my code:
function drawChart() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Percentile', 'Number of students', 'Vertical lines',{ role: 'style' }],
[1, 0.2020202,,''],
[3, 0.546875,,''],
[10, 1.20967742,,''],
[25, 1.87969925,,''],
[50, 1.953125, ,''],
[75, 1.32743363,,''],
[90, 0.64814815, ,''],
[97, 0.25316456, ,''],
[99, 0.00621891,,''],
[78, ,20,'stroke-width: 2; fill-color: red']
]);
var options = {
vAxis: {
gridlines:{count: 6},
viewWindow:{ max: 2.5}
},
hAxis: {
ticks: [0,20,40,60,80,100,120]
},
seriesType: 'line',
series: {1: {type: 'bars'}},
bar:{groupWidth:2},
intervals: { 'lineWidth':2, 'barWidth': 0.5, style: 'boxes' },
curveType: 'function',
legend: { position: 'none' },
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ComboChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
Please suggest how can these vertical bands be achieved?

Sinatra to Google Geochart - Passing Data

I am new to web development, and I am trying to create a Sinatra app. In my app, I have an instance variable that references a two-dimensional array like so:
#my_var = [ ['NY', 55], ['NJ', 37] ]
I am also using the Google Charts API to create some visualizations with my data; in particular, I am trying to use the Geochart library in my view to create a state-by-state heat map of the U.S.
I'd like to use the array mentioned earlier (#my_var) in my template to populate the Google DataTable that's used to create the chart. My DataTable will have two columns, the first representing state and the second representing score, and I would like each nested array in #my_var to map to these two columns like so:
STATE SCORE
NY 55
NJ 37
Does anybody know how to do this? As far as I can see from the documentation, you have to populate the table with static values. I'm not sure how to pass the data from my application (Ruby code) to the processes that create the chart (Javascript code).
To further complicate the matter, I'm creating my template with haml. What I have so far is this:
%script{ :type => "text/javascript" }
:plain
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = new google.visualization.DataTable();
data.addRows(2);
data.addColumn('string', 'State');
data.addColumn('number', 'Score');
data.setValue(0, 0, 'NY');
data.setValue(0, 1, 55);
data.setValue(1, 0, 'NJ');
data.setValue(1, 1, 37);
var options = {region: 'US',
resolution: 'provinces',
backgroundColor: '#CCC',
colors: ['red','blue'],
width: 500,
height: 370};
var container = document.getElementById('map_canvas');
var geochart = new google.visualization.GeoChart(container);
geochart.draw(data, options);
};
The map is rendered with the correct size and the correct colors in the legend. However, I'm not seeing NY or NJ colored in. Also note that I'm using static values here--I want to get this step down before trying to create the table dynamically.
Any help would be appreciated.
I figured out how to populate the table. I used Ruby interpolation to convert the Ruby array into a Javascript array, and then used the JS array to fill the DataTable like so:
%script{ :type => "text/javascript" }
:plain
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = new google.visualization.DataTable();
var scores_by_state = #{#scores_by_state}
data.addRows(scores_by_state.length)
data.addColumn('string', 'State');
data.addColumn('number', 'Average Score');
for(var i = 0; i < scores_by_state.length; i++)
{
data.setValue(i, 0, scores_by_state[i][0]);
data.setValue(i, 1, scores_by_state[i][1]);
}
var options = {region: 'US',
resolution: 'provinces',
backgroundColor: '#CCC',
colors: ['red','blue'],
width: 500,
height: 370};
var container = document.getElementById('map_canvas');
var geochart = new google.visualization.GeoChart(container);
geochart.draw(data, options);
};