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();
}
Related
I am a newbie to front end development. I am trying a demo example given on Google charts website. I am reading data from a csv file and able to generate a horizontal bar graph. Now i want to give colors to those bars but don't want to write those column names every time.
Below is the code i am referring to. How to read column names run time and color those bars?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.get("name.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
var data = new google.visualization.arrayToDataTable(arrayData);
var view = new google.visualization.DataView(data);
view.setColumns([0,1]);
var options = {
title: "Your data in bar format" ,
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(view, options);
} );
}
looking at the code, the bars are actually represented by rows, not columns.
there are only two columns in the DataView --> view.setColumns([0, 1]);
first column is the name, second the value...
when using rows for the bars, the only way to provide a specific color,
is to use a 'style' column,
you can add using a calculated column in the DataView.
the style column should follow the series column
i'm not sure how you want to assign each color,
but here is an example of adding the calculated 'style' column.
you can read the name using --> dt.getValue(row, 0)
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
role: 'style',
type: 'string',
calc: function (dt, row) {
var color;
switch (dt.getValue(row, 0)) {
case 'A':
color = 'red';
break;
case 'B':
color = 'blue';
break;
default:
color = 'green';
}
return color;
}
}]);
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>
I use a google maps ColumnChart to reprensent the elevation in a map.
I also use a mouseover to print info and show the correspondent position.
When a column in the chart is clicked, it popups an info balloon, like here:
http://4.bp.blogspot.com/-4I8oi3WqY5o/UIZnzbXql_I/AAAAAAAAAcE/GO4wl6I2-lM/s1600/Charts.png
This balloon is ok for desktops, but a pain for mobile (very hard to close, etc).
How can I completely disable it? It has to do with the second data column passed to the chart.
No balloons!
Thanks!
L.
EDIT
Code added by request:
var option = {
legend: 'none',
backgroundColor: 'transparent',
colors: ["#C9CFF5"],
titleColor: '#C9CFF5',
focusBorderColor: '#00AA00',
titleY: 'Elevation (m)',
tooltip: { trigger: 'none' },
bar: { groupWidth: '100%' }
}
// Build data
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation (m):');
for (var i = 0; i < trackmarks.length; i++) {
data.addRow(['', trackaltis[i]]);
}
// Draw the chart using the data within its DIV.
chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));
chart.draw(data, option);
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.
Is it possible to develop a threshold with Google Charts?
I have a Google combo chart with 5 columns. In theory, I wanted to use the addRange formatter function to change the color of the 2nd column if it was under 50. (Basically it's a motivation tool. Your daily goal is to make atleast 50 calls. If you do not, the chart shows up as red, if you do, then it is the default color)
This is my current code that creates the chart, just not the formatting. Thanks.
// 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() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Rep');
data.addColumn('number', 'Yesterday');
data.addColumn('number', 'Last 7');
data.addColumn('number', 'Last 30');
data.addColumn('number', 'The Bar');
$("#data-table thead th").each(function(){
var initials = $(this).text();
var yesterday = parseInt($("." + initials + ".Yesterday").text());
var seven = parseInt($("." + initials + ".seven").text());
var thirty = parseInt($("." + initials + ".thirty").text());
data.addRow([initials, yesterday, seven, thirty, 50]);
});
// Set chart options
var title = $("#data-table caption").text();
var options = {'title':title,
seriesType: 'bars',
series: {3: {type: "line"}},
hAxis: {title: 'Rep'},
vAxis: {title: 'Outbound Calls'}
};
var formatter = new google.visualization.TableColorFormat();
formatter.addRange(50,0, 'red', '#000');
formatter.format(data, 1);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ComboChart(document.getElementById('call-log'));
chart.draw(data, options);
}
The easiest way to do this is to do a quick check on your data, and set a variable for the color of series two based on what the value of that column is.
So currently you have the following options code:
var options = {'title':title,
seriesType: 'bars',
series: {3: {type: "line"}},
hAxis: {title: 'Rep'},
vAxis: {title: 'Outbound Calls'}
};
If you change this slightly, you can make series 2 colored based on a variable:
var options = {'title':title,
seriesType: 'bars',
series: {
3: {type: "line"}
// set the color of column 2 (series #1) via variable
1: {color: colorvar}
},
hAxis: {title: 'Rep'},
vAxis: {title: 'Outbound Calls'}
};
Then you can just create a javascript function to determine what the value for column 2 is, and color appropriately:
var colorvar = "#FF0000";
if (data.getValue(0,1) >= 50)
colorvar = "#000000";
This way, if the value is under 50, it will be read. Otherwise it will change to black. Then when you create the options, it will use whatever color is dictated by this function. That way you can color based on the value in column 2.