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);
};
Related
First of all, I am not sure if what I am looking for is called stacked column chart or else.
Lib is either Google Charts or amCharts.
I have a series of values for the last 28 days representing e-mails sent, e-mails opened and e-mails with links clicked. For each date, the column's max. value should be the number of e-mails sent. This column is then divided based on the two other values. Basically what the chart should show is that from 20 mails sent, 17 were opened and 5 even had people click links inside them.
With a regular stacked column approach and the numbers 20, 17 and 5, this would render a column peaking at 42 with one section covering 0-20, one 20-37 and one 37-42.
What I want is a column peaking at 20, in front of it a column peaking at 17 and in front of that a column peaking at 5. Similar to a diff chart.
I could theoretically achieve this by modifying my data taking the 5 mails with clicks, the opened mails are 17 minus 5 = 12 and the mails sent are 20 minus 17 = 3. Then 5+12+3 = 20 what I wanted. However, hovering the stacked column will display the wrong values 5, 12 and 3 in the tooltip instead of 5, 17 and 20. So I would have to render custom tooltips.
You guys have any idea if there is a simple solution for my problem?
for the scenario you describe theoretically,
you would not need custom tooltips.
when loading the google data table, we can use object notation.
we can provide the value (v:), and the formatted value (f:)
{v: 12, f: '17'}
the tooltip will use the formatted value by default.
in addition, you could use a DataView to perform the calculation.
which would allow you to load the data as normal.
here, calculated columns are used to adjust the value that is plotted,
but display the original value.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// create data table
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Emails with Clicks');
data.addColumn('number', 'Emails Opened');
data.addColumn('number', 'Emails Sent');
// add data
data.addRow(['06/2020', 5, 17, 20]);
// create number format
var formatNumber = new google.visualization.NumberFormat({
pattern: '#,##0'
});
// create data view
var view = new google.visualization.DataView(data);
// build view columns
var viewColumns = [0];
for (var i = 1; i < data.getNumberOfColumns(); i++) {
addColumn(i);
}
function addColumn(index) {
viewColumns.push({
calc: function (dt, row) {
var currentColumnValue = dt.getValue(row, index);
var previousColumnValue = 0;
if (index > 1) {
previousColumnValue = dt.getValue(row, index - 1);
}
var adjusttedColumnValue = currentColumnValue - previousColumnValue;
var formattedColumnValue = formatNumber.formatValue(currentColumnValue);
return {
v: adjusttedColumnValue,
f: formattedColumnValue
};
},
label: data.getColumnLabel(index),
type: data.getColumnType(index),
});
}
// set view columns
view.setColumns(viewColumns);
// create options
var options = {
chartArea: {
left: 64,
top: 40,
right: 32,
bottom: 40,
height: '100%',
width: '100%'
},
height: '100%',
isStacked: true,
legend: {
alignment: 'end',
position: 'top'
},
width: '100%'
};
// create, draw chart with view
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
window.addEventListener('resize', function () {
chart.draw(view, options);
});
});
html, body {
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
}
.chart {
height: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="chart" id="chart_div"></div>
Note: If you want to stack columns, one in front of the other, similar to a Diff Chart,
check this answer...
Google Chart - More then 1 difference column
I have a question about why a way that I'm trying to add polylines as a layer isn't working. To be clear, I'm not trying to assert that it should be working, just that I'm curious why it works in one case but not in another. Consider the following code:
var oMbTiles = new L.tileLayer('/mbtiles/mbtiles.php?&z={z}&x={x}&y={y}', {
tms: true,
opacity: 0.7
}),
oUpIcon = new L.Icon({
iconUrl: '/custom/css/themes/app/markers/up.png',
iconSize: [24, 26]
}),
oMapTypes = {
'Yakabox': oMbTiles
},
aFirstMarkers = [],
aFirstLines = [],
aFirstLatLng,
oFirstLine,
oFirstGroup,
oLayersControl,
oOverlayMaps,
oMap,
i;
aFirstLatLng = [
[18.319026, -66.420557],
[18.180555, -66.749961],
[18.361945, -67.175597],
[18.455183, -67.119887],
[18.158345, -66.932911],
[18.295366, -67.125135],
[18.402253, -66.711397],
[18.420412, -66.671979],
[18.445147, -66.559696],
[17.991245, -67.153993],
[18.083361, -67.153897],
[18.064919, -66.716683],
[18.412600, -66.863926],
[18.190607, -66.832041],
[18.076713, -66.947389],
[18.295913, -66.515588],
[18.263085, -66.712985],
[18.433150, -66.285875],
[17.963613, -66.947127],
[18.349416, -66.578079],
[18.448452, -66.594127],
[17.985033, -66.886536],
[18.053539, -66.792931],
[18.407226, -66.808999],
[18.134695, -67.116199],
[18.468320, -67.015781],
[18.210330, -66.591616],
[18.003422, -67.035810],
[18.277102, -66.869645],
[18.240187, -66.988776],
[18.422908, -66.489337],
[18.377637, -67.079574],
[18.332568, -67.227022],
[18.434099, -66.927384],
[18.182055, -67.132502],
[18.221464, -67.156039],
[18.107800, -67.037263],
[18.332929, -66.959689]
];
for (i = 0; i < aFirstLatLng.length; i++) {
aFirstMarkers.push(L.marker(aFirstLatLng[i]).setIcon(oUpIcon).bindPopup('lat/lng : ' + aFirstLatLng[i].join(', ')))
if (i === (aFirstLatLng.length - 1)) {
aFirstLines.push(L.polyline([aFirstLatLng[i], aFirstLatLng[0]], {color: 'red', weight: 3, opacity: 0}));
} else {
aFirstLines.push(L.polyline([aFirstLatLng[i], aFirstLatLng[i + 1]], {color: 'red', weight: 3, opacity: 0}));
}
}
oFirstLine = L.polyline(aFirstLatLng, {
weight: 5,
color: 'red'
});
oFirstLine.on('click', function () {
console.log('Clicked First line', arguments);
});
oFirstGroup = L.layerGroup(aFirstMarkers, {});
// This works
oFirstGroup.addLayer(oFirstLine);
// These next two lines do not work
// Here I'm trying to just add an array of polyline objects as a layer
//oFirstGroup.addLayer(aFirstLines);
// Here I'm trying to add the array of polyline objects as a layer group
//oFirstGroup.addLayer(L.layerGroup(aFirstLines));
oOverlayMaps = {
'First Group': oFirstGroup,
};
oMap = new L.map('map', {
minZoom: 4,
maxZoom: 10,
zoom: 9,
center: aFirstLatLng[7],
layers: [oMbTiles, oFirstGroup]
});
oLayersControl = new L.Control.Layers(oMapTypes, oOverlayMaps, {
collapsed: false
}).addTo(oMap);
So here, I'm just trying to iterate through some zip codes, create markers for each location, and connect the markers using polylines. If I instantiate the polyline object using only the array of lat/lng, that works when I add that polyline to the markers layer group (oFirstGroup). But if I pass in an array of polyline objects (which were passed in the start/end lat/lng coordinates), that doesn't work. The lines do not show up on the map. This is because I get an error saying "The provided object is not a layer". Ok, so I try to explicitly create a layer group using that array of polyline objects and while the error goes away, the lines are still not added to the map.
So I'm curious, should that be working? Or is it the case that the only way to properly create a polyline connecting markers is by passing the lat/lng coordinates as an array when instantiating a single polyline object for adding to the layer? Why is it that I can pass in an array of marker objects (when instantiating oFirstGroup) and add that layer to the map but I can't do the same thing when passing in an array of polyline objects?
thnx,
Christoph
Ok, I'm not ashamed to admit it -- I'm a moron. The problem was opacity: 0. I copied the code from elsewhere (to try to understand what was going on) and I didn't remove that. As soon as I did, voila!
I iz be dumm.
thnx,
Christoph
I have a data table that is used for a pie chart and I need to set colors of slices based on a value in a row. For example, I have a table of car sales by type (e.g. lease, cash, finance) and I want to specify a color for each one. In the documentation, it seems possible to do this with bar charts, but I can't seem to do it with slices. I tried the following:
var pieChart = new google.visualization.ChartWrapper({
options : {
...
slices: [{color: 'black'}, {color: 'green'}, {color: 'red'}]
}
});
The colors get rendered but I want to specify black for lease. Any ideas on how I can get this to work?
the colors in the slices array should be in the same order as the rows in the data table
so, with the following rows...
data.addRows([
['Cash', 5],
['Finance', 20],
['Lease', 15]
]);
for 'Lease' to black, it should be the last color in the array
slices: [{color: 'green'}, {color: 'red'}, {color: 'black'}]
if the order of the rows is unknown, you could set the colors dynamically
use an object to create a map for the colors
// create color map
var colors = {
'Cash': 'green',
'Finance': 'red',
'Lease': 'black'
};
then build the slices array based on the values in the data table
// build slices
var slices = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
slices.push({
color: colors[data.getValue(i, 0)]
});
}
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'sales');
data.addColumn('number', 'count');
data.addRows([
['Cash', 5],
['Finance', 20],
['Lease', 15]
]);
data.sort([{column: 1, desc: true}]);
// create color map
var colors = {
'Cash': 'green',
'Finance': 'red',
'Lease': 'black'
};
// build slices
var slices = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
slices.push({
color: colors[data.getValue(i, 0)]
});
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(container);
chart.draw(data, {
slices: slices
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
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>
I am using GWT api for google charts and having some issues:
colums from the start and end values missing for the column chart
BarChart width is trimmed is half for first/last value
To solve this I tried viewWindowMode property
HorizontalAxisOptions opt = HorizontalAxisOptions.create();
opt.set("viewWindowMode","pretty");
but this does not work.
Any ideas on how to solve?
Code:
private Options createOptions(ChartDataProxy response) {
Options options = Options.create();
options.setWidth(chartPanel.getOffsetWidth() - 2 * chartBorderWidth);
options.setHeight(chartPanel.getOffsetHeight() - 2 * chartBorderWidth);
HorizontalAxisOptions opt = HorizontalAxisOptions.create();
opt.setTitle(response.getxAxisName());
opt.setSlantedText(true);
opt.set("viewWindowMode","pretty");
options.setHAxisOptions(opt);
AxisOptions vopt = AxisOptions.create();
vopt.setTitle( response.getyAxisName());
vopt.set("viewWindowMode","pretty");
options.setVAxisOptions(vopt);
options.setTitle(response.getCaption() + " " + response.getSubCaption());
options.setLegend( LegendPosition.BOTTOM );
options.setPointSize(4);
return options;
}
I'm having similar problem, although I was using javascript. Maybe, you can adapt it into GWT.
Basically DataView can fix it. You just need to handle the first column with DataView and return whatever you need to return when not using DataView -- however, as string. I (don't) know, it's weird.
Given I had two columns: date, number. I will use this kind of code:
var data = new google.visualization.DataTable();
data.addColumn('date', 'month');
data.addColumn('number', 'users');
// trick to prevent the bar chart from being cut in half at both edge of our graph
var dataView = new google.visualization.DataView(data);
dataView.setColumns([{calc: function(data, row) { return data.getFormattedValue(row, 0); }, type:'string'}, 1]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_monthly_users'));
chart.draw(dataView, options);
Hope it helps. I merely gather the scattered solutions.