When a State of the US is selected from a dropdown containing all the states, I wish to show that state highlighted in the US map. I want to accomplish this using Geo Chart of the Google Charts API.
While trying to achieve that, I tried this sample in the Google Code Playground (where you can edit existing samples)
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country'],
['US-AK' ],
['US-AZ' ],
['US-HI' ],
]);
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, {region:"US",legend:"none",width: 556, height: 347});
}
Although Alaska ('US-AK') & Hawaii ('US-HI') show up in the map, Arizona ('US-AZ' ) doesn't. How can I get Arizona to be highlighted as well? I'll also appreciate any pointers on my original goal of showing a state highlighted dynamically when a state within the dropdown is chosen.
The reason Arizona doesn't show up on the map is because you have to set the resolution option to "provinces" to get a map of the states. Using a dropdown to highlight a selected state is a bit more complex, but certainly doable. Here's one way you could do it; in your javascript:
function drawChart () {
var data = google.visualization.arrayToDataTable([
['State', ''],
['US-AK', 0],
['US-AZ', 0],
['US-HI', 0]
]);
var geochart = new google.visualization.GeoChart(document.getElementById('chart_div'));
var options = {
region:"US",
legend:"none",
width: 556,
height: 347,
resolution: 'provinces',
colorAxis: {
minValue: 0,
maxValue: 1,
colors: ['green', 'red']
}
};
var stateSelector = document.querySelector('#state');
function updateChart () {
var index = this.selectedIndex;
var selectedState = this.options[index].value;
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
calc: function (dt, row) {
return (dt.getValue(row, 0) == selectedState) ? 1 : 0;
}
}]);
geochart.draw(view, options);
}
if (document.addEventListener) {
stateSelector.addEventListener('change', updateChart, false);
}
else if (document.attachEvent) {
stateSelector.attachEvent('onchange', updateChart);
}
else {
stateSelector.onchange = updateChart;
}
geochart.draw(data, options);
}
google.load('visualization', '1', {packages:['geochart'], callback: drawChart});
And then in your HTML:
<select id="state">
<option value="" selected="selected">Select a state to highlight</option>
<option value="US-AK">Alaska</option>
<option value="US-AZ">Arizona</option>
<option value="US-HI">Hawaii</option>
</select>
<div id="chart_div"></div>
Here's a jsfiddle of this that you can play around with: http://jsfiddle.net/asgallant/wwDyU/
No need to add states code for US or any country. You can give full names of states in US as is and just one modification in your code.
Just change the options like this....
var options={
region:"US",
resolution: 'provinces',//This is the property due to which U can see regions.
colors:['green', 'red'],
dataMode:'regions'
}
Related
I've tried every configuration possible to get a Google Area Chart to display a single point but nothing has worked. I'm also totally open to any solutions using the Google Line Chart as long as it has a filled area. However, I couldn't find a solution for making this work with a line chart either.
Already tried setting the pointSize as well as setting the pointSize conditionally if there is only a single row. Tried numerous different ways of configuring the chart including.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Updated');
data.addColumn('number', 'Amount');
data.addRow([new Date(1548266417060.704),100]);
AND
var mets = [['Updated', 'Amount'], [new Date(1548266417060.704),100]];
var data = google.visualization.arrayToDataTable(mets);
Area Chart Example JSFiddle
Line Chart Example JSFiddle
This Line Chart would need the area below the line filled in but I haven't been able to determine how to do so with this API
Example of the chart I'm trying to achieve using CanvasJs but I'm trying to implement it with Google Visualization API and allow for a single point to be shown if there is only a single point on the chart.
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100],
//[new Date(1548716961817.513),100],
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
pointSize: 5,
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I'm expecting the chart to display a single point when there is only one data row. As you can see by the JSFiddle when there is a single row nothing appears but as soon as you uncomment the second row everything works just fine.
there is a bug with the most recent version of google charts,
when the x-axis is a continuous axis (date, number, not string, etc.),
and only one row exists in the data table,
you must set an explicit view window on the axis --> hAxis.viewWindow
to use a date type with only one row,
first, use data table method --> getColumnRange
this will return an object with min & max properties for the x-axis
then we can increase the max and decrease the min by one day,
and use that for our view window.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100]
]);
var oneDay = (24 * 60 * 60 * 1000);
var dateRange = data.getColumnRange(0);
if (data.getNumberOfRows() === 1) {
dateRange.min = new Date(dateRange.min.getTime() - oneDay);
dateRange.max = new Date(dateRange.max.getTime() + oneDay);
}
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {color: '#333'},
viewWindow: dateRange
},
pointSize: 5
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
you'll notice if we go back to an old version ('45'),
a single date row displays without issue...
google.charts.load('45', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {color: '#333'},
},
pointSize: 5
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I dont know if you understod but the date format you are passing is wrong, so when you write Date() it return the current date formatted as string.
now if we understand that much then the currect way of writing the date array should be
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704).toString(),100],
]);
This will return the date formatted as string.
and the library will accept it.
if you are still want to pass on an object then you need to specify the dataTable column as Date.
read here for more information
https://developers.google.com/chart/interactive/docs/datesandtimes
I am having a bit of an issue with the Google Visualization library. I have a very simple table being built on the screen, and I need to disable sorting, but only for a certain column. I have gone through their documentation and found that you can define your own functions for events that will override the default, but it is not working. Here is an extremely simple example...
var chart = new google.visualization.Table(document.getElementById('myTable'));
google.visualization.events.addListener(chart, 'sort', function(e) { handleSort(e, chart); });
chart.draw(opts, dataTable);
function handleSort(e, chart) {
console.log('inside sort');
return false;
}
when I click on the column header I get the console log of 'inside sort', but the table will sort on that column. I have even tried...
function handleSort(e, chart) {
if(e.column == 9) {
chart.options['sortColumn'] = 0;
chart.options['isAscending'] = true;
}
}
When clicking the column header for column 9 it still sorts on column 9. I can't get it to stop sorting on that column. Essentially I have a button in the header for column 9, when the user clicks the button the page does something, but since it sorts the table, it ruins what is supposed to be happening.
Also, inside the opts object that gets passed to the draw method, I do have 'sort' set to 'event' like they say in their documentation, but it will not work. The function gets run, but the table still sorts regardless of what I have in the function. Any help would be greatly appreciate. Thank you all.
If you want complete control over the sort, add sort: 'event' to the configuration options
Keep in mind, you're in control now, so you must sort the data manually.
The sortAscending and sortColumn options are used to set the sort arrow in the column heading.
In this example, the data is initially sorted by descending Hours, set the options accordingly on the initial draw.
Then in the sort event, I only allow sorting by Hours...
google.load("visualization", "1", {packages:["table"], callback: loadChart});
function loadChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('number', 'Hours');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, 40],
['Jim', {v:8000, f: '$8,000'}, 30],
['Alice', {v: 12500, f: '$12,500'}, 20],
['Bob', {v: 7000, f: '$7,000'}, 10]
]);
var chart = new google.visualization.Table(document.getElementById('table_div'));
var options = {
sort: 'event',
sortAscending: false,
sortColumn: 2
};
google.visualization.events.addListener(chart, 'sort', function(e) {
if (e.column === 2) {
options.sortAscending = e.ascending;
options.sortColumn = e.column;
data.sort([{
column: e.column,
desc: !e.ascending
}]);
chart.draw(data, options);
}
});
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>
Using the Google Charts API [https://developers.google.com/chart/interactive/docs/events] I have a properly formatted ComboChart and a properly formatted google rendered data table.
I am able to use the setSelection() function - However, the selection is highlighting my average line which runs through the middle of the bar chart.
I am unable to work out how to make the highlighted 'dot' on the chart/graph area appear on the other series/data set (e.g highlight the bars instead of the average line - which as per any average, is a straight line through the middle which means nothing to my end user).
I can add some code to a JS fiddle if you wish but it's really just a basic google combo chart displaying several different bars as my main data set and an average line as my series '1' (with base 0).
Edit: add js fiddle: http://jsfiddle.net/GSryX/
[code]
some code
[/code]
Any ideas?
When setting the selection, make sure the "column" parameter of the selected object refers to the correct column in your DataTable.
Edit:
If the bars are too small to show the selection effect, you can instead use a hack like this http://jsfiddle.net/asgallant/5SX8w/ to change the bar color on selection. This works best when you have only 1 series of data; if you have more than 1 series, it requires modification, and may not display properly unless you are using stacked bars.
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addRows([
['Foo', 94],
['Bar', 23],
['Baz', 80],
['Bat', 47],
['Cad', 32],
['Qud', 54]
]);
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
dataTable: data,
options: {
// setting the "isStacked" option to true fixes the spacing problem
isStacked: true,
height: 300,
width: 600,
series: {
1: {
// set the color to change to
color: '00A0D0',
// don't show this in the legend
visibleInLegend: false
}
}
}
});
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getChart().getSelection();
if (selection.length > 0) {
var newSelection = [];
// if row is undefined, we selected the entire series
// otherwise, just a single element
if (typeof(selection[0].row) == 'undefined') {
newSelection.push({
column: 2
});
chart.setView({
columns: [0, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () {
// this series is just a placeholder
return 0;
}
}, 1]
});
}
else {
var rows = [];
for (var i = 0; i < selection.length; i++) {
rows.push(selection[i].row);
// move the selected elements to column 2
newSelection.push({
row: selection[i].row,
column: 2
});
}
// set the view to remove the selected elements from the first series and add them to the second series
chart.setView({
columns: [0, {
type: 'number',
label: data.getColumnLabel(1),
calc: function (dt, row) {
return (rows.indexOf(row) >= 0) ? null : {v: dt.getValue(row, 1), f: dt.getFormattedValue(row, 1)};
}
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function (dt, row) {
return (rows.indexOf(row) >= 0) ? {v: dt.getValue(row, 1), f: dt.getFormattedValue(row, 1)} : null;
}
}]
});
}
// re-set the selection when the chart is done drawing
var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runOnce);
chart.getChart().setSelection(newSelection);
});
}
else {
// if nothing is selected, clear the view to draw the base chart
chart.setView();
}
chart.draw();
});
chart.draw();
}
I want to change the color of each bar in my bar graph. Currently, I tried setting the colors option as specified in the documentation:
var options = {
'title' : results.title,
'width' : 400,
'height' : 300,
'is3D' : true,
'colors' : ["#194D86","#699A36", "#000000"],
'allowHtml' : true
}
But it does not work. Basically, I would want each bar in the following graph to be the same color: http://jsfiddle.net/etiennenoel/ZThMp/12/
Is there a way to do that or do I have to change my code structure to do so ?
[Edit - there is a better method outlined in edit below]
The Visualization API colors data by series (or column in the DataTable, if you prefer). The solution is to split the data into multiple series using a DataView:
// get a list of all the labels in column 0
var group = google.visualization.data.group(data, [0], []);
// build the columns for the view
var columns = [0];
for (var i = 0; i < group.getNumberOfRows(); i++) {
var label = group.getValue(i, 0);
// set the columns to use in the chart's view
// calculated columns put data belonging to each label in the proper column
columns.push({
type: 'number',
label: label,
calc: (function (name) {
return function (dt, row) {
return (dt.getValue(row, 0) == name) ? dt.getValue(row, 1) : null;
}
})(label)
});
}
// create the DataView
var view = new google.visualization.DataView(data);
view.setColumns(columns);
Set the "isStacked" option in the chart to "true" to fix the column spacing issues that result, and draw the chart using the view instead of the DataTable:
var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
chart.draw(view, {
// options
isStacked: true
});
See an example here.
[Edit: new (improved) method available with update to the Visualization API]
You can now use the new "style" column role to specify styles for your columns. It works like this:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addColumn({type: 'string', role: 'style'});
data.addRows([
['Foo', 5, 'color: #ac6598'],
['Bar', 7, 'color: #3fb0e9'],
['Baz', 3, 'color: #42c698']
]);
var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 400,
width: 600,
legend: {
position: 'none'
}
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
see example here: http://jsfiddle.net/asgallant/gbzLB/
There is a solution for your problem.You need to add series in your options. I have already answered for the similar type of question. Refer my answer here. I hope this will help you.
I have been playing around with Google charts quite a bit over in the google charts play ground here:
Link
The code I have been playing with is this:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Austria'],
['2003', 1336060],
['2004', 1538156],
['2005', 1576579],
['2006', 1600652],
['2007', 1968113],
['2008', 1901067]
]);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year"},
hAxis: {title: "Cups"}}
);
}
and that gives me a nice chart that looks like this:
I am trying to have this chart fit the needs of my website, and to do this, I need to make the bar names on the left links to another page. So for example 2003 would be a link that the user can click ans so would 2004 etc.
I tried to do something like this:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Austria'],
['Link text', 1336060],
['2004', 1538156],
['2005', 1576579],
['2006', 1600652],
['2007', 1968113],
['2008', 1901067]
]);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year"},
hAxis: {title: "Cups"}}
);
}
But I could only hope for it to be that easy and it wasn't. Does anyone know if this is at all possible?
Manzoid's answer is good, but "some assembly is still required" as it just displays an alert box rather than following the link. Here is a more complete answer BUT it makes the bars clickable rather than the labels. I create a DataTable that includes the links then create a DataView from that to select the columns I want to display. Then when the select event occurs, I just retrieve the link from the original DataTable.
<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([
['Year', 'link', 'Austria'],
['2003', 'http://en.wikipedia.org/wiki/2003', 1336060],
['2004', 'http://en.wikipedia.org/wiki/2004', 1538156],
['2005', 'http://en.wikipedia.org/wiki/2005', 1576579],
['2006', 'http://en.wikipedia.org/wiki/2006', 1600652],
['2007', 'http://en.wikipedia.org/wiki/2007', 1968113],
['2008', 'http://en.wikipedia.org/wiki/2008', 1901067]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 2]);
var options = {title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year"},
hAxis: {title: "Cups"}};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(view, options);
var selectHandler = function(e) {
window.location = data.getValue(chart.getSelection()[0]['row'], 1 );
}
google.visualization.events.addListener(chart, 'select', selectHandler);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 900px;"></div>
</body>
</html>
This is non-trivial because the output you are seeing is SVG, not HTML. Those labels in your example ("2004", "2005", etc) are embedded inside SVG text nodes, so inserting raw HTML markup inside them will not be rendered as HTML.
The workaround is to scan for the text nodes containing the target values (again, "2004", "2005" etc) and replace them with ForeignObject elements. ForeignObject elements can contain regular HTML. These then need to be positioned more-or-less where the original SVG text nodes had been.
Here is a sample snippet illustrating all this. It is tuned to your specific example, so when you switch to rendering whatever your real data is, you will want to modify and generalize this snippet accordingly.
// Note: You will probably need to tweak these deltas
// for your labels to position nicely.
var xDelta = 35;
var yDelta = 13;
var years = ['2003','2004','2005','2006','2007','2008'];
$('text').each(function(i, el) {
if (years.indexOf(el.textContent) != -1) {
var g = el.parentNode;
var x = el.getAttribute('x');
var y = el.getAttribute('y');
var width = el.getAttribute('width') || 50;
var height = el.getAttribute('height') || 15;
// A "ForeignObject" tag is how you can inject HTML into an SVG document.
var fo = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject")
fo.setAttribute('x', x - xDelta);
fo.setAttribute('y', y - yDelta);
fo.setAttribute('height', height);
fo.setAttribute('width', width);
var body = document.createElementNS("http://www.w3.org/1999/xhtml", "BODY");
var a = document.createElement("A");
a.href = "http://yahoo.com";
a.setAttribute("style", "color:blue;");
a.innerHTML = el.textContent;
body.appendChild(a);
fo.appendChild(body);
// Remove the original SVG text and replace it with the HTML.
g.removeChild(el);
g.appendChild(fo);
}
});
Minor note, there is a bit of jQuery in there for convenience but you can replace $('text') with document.getElementsByTagName("svg")[0].getElementsByTagName("text").
Since the SVG-embedding route is (understandably) too hairy for you to want to muck with, let's try a completely different approach. Assuming that you have the flexibility to alter your functional specification a bit, such that the bars are clickable, not the labels, then here's a much simpler solution that will work.
Look for the alert in this snippet, that's the part that you will customize to do the redirect.
function drawVisualization() {
// Create and populate the data table.
var rawData = [
['Year', 'Austria'],
['2003', 1336060],
['2004', 1538156],
['2005', 1576579],
['2006', 1600652],
['2007', 1968113],
['2008', 1901067]
];
var data = google.visualization.arrayToDataTable(rawData);
// Create and draw the visualization.
var chart = new google.visualization.BarChart(document.getElementById('visualization'));
chart.draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year"},
hAxis: {title: "Cups"}}
);
var handler = function(e) {
var sel = chart.getSelection();
sel = sel[0];
if (sel && sel['row'] && sel['column']) {
var year = rawData[sel['row'] + 1][0];
alert(year); // This where you'd construct the URL for this row, and redirect to it.
}
}
google.visualization.events.addListener(chart, 'select', handler);
}
I apparently don't have enough reputation points to comment directly to a previous reply, so my apologies for doing so as a new post. manzoid's suggestion is great but has one issue I found, and it looks like Mark Butler might have run into the same problem (or unknowingly sidestepped it).
if (sel && sel['row'] && sel['column']) {
That line keeps the first data point from being clickable. I used it on a Jan-Dec bar chart, and only Feb-Dec were clickable. Removing sel['row'] from the condition allows Jan to work. I don't know that the if() condition is really even necessary, though.
Here's another solution that wraps each text tag for label with anchor tag.
no ForeignObject
clickable label
stylable by css (hover effect)
Here's a sample: https://jsfiddle.net/tokkonoPapa/h3eq9m9p/
/* find the value in array */
function inArray(val, arr) {
var i, n = arr.length;
val = val.replace('…', ''); // remove ellipsis
for (i = 0; i < n; ++i) {
if (i in arr && 0 === arr[i].label.indexOf(val)) {
return i;
}
}
return -1;
}
/* add a link to each label */
function addLink(data, id) {
var n, p, info = [], ns = 'hxxp://www.w3.org/1999/xlink';
// make an array for label and link.
n = data.getNumberOfRows();
for (i = 0; i < n; ++i) {
info.push({
label: data.getValue(i, 0),
link: data.getValue(i, 2)
});
}
$('#' + id).find('text').each(function(i, elm) {
p = elm.parentNode;
if ('g' === p.tagName.toLowerCase()) {
i = inArray(elm.textContent, info);
if (-1 !== i) {
/* wrap text tag with anchor tag */
n = document.createElementNS('hxxp://www.w3.org/2000/svg', 'a');
n.setAttributeNS(ns, 'xlink:href', info[i].link);
n.setAttributeNS(ns, 'title', info[i].label);
n.setAttribute('target', '_blank');
n.setAttribute('class', 'city-name');
n.appendChild(p.removeChild(elm));
p.appendChild(n);
info.splice(i, 1); // for speeding up
}
}
});
}
function drawBasic() {
var data = google.visualization.arrayToDataTable([
['City', '2010 Population', {role: 'link'}],
['New York City, NY', 8175000, 'hxxp://google.com/'],
['Los Angeles, CA', 3792000, 'hxxp://yahoo.com/' ],
['Chicago, IL', 2695000, 'hxxp://bing.com/' ],
['Houston, TX', 2099000, 'hxxp://example.com'],
['Philadelphia, PA', 1526000, 'hxxp://example.com']
]);
var options = {...};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
addLink(data, 'chart_div');
}
You should use formatters.
If you replace value with HTML then sorting will not work properly.