Google Charts - Change the color of bars - javascript

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.

Related

How to add color to horizontal bar graphs created by giving csv as an input using google charts?

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;
}
}]);

Google Bar Chart max bar width

I have a Google Bar Chart inside a fixed-width div. In some cases, I have many bars, but sometimes I only get 1 or 2 bars. The problem is that in this case, I got a chart like this:
I would like to set a max bar width, so that when I have only one bar, it doesn't take the whole container width. Do you know how to achieve that please?
[edit] I am looking for a solution for a Material chart (google.charts.Bar)
The solution is to add blank columns when there are not enough columns initially.
for (var i = 0; i < n; i++) {
if (i % 2 == 0)
rows.push([" ", null])
else
rows.unshift([" ", null])
}
dataTable.addRows(rows);
bar.groupWidth option doesn't work on Material charts
even with google.charts.Bar.convertOptions
tried versions '41' thru 'current'
example...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Motivation Level');
data.addRows([
['10h', 5]
]);
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions({
bar: {
groupWidth: 20
}
}));
},
packages: ['bar']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Edit
only other option would be to modify the SVG directly when the chart's 'ready' event fires
but this is not recommended
see following example...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Motivation Level');
data.addRows([
['10h', 5]
]);
var container = document.getElementById('chart_div');
var chart = new google.charts.Bar(container);
// modify SVG on 'ready'
google.visualization.events.addListener(chart, 'ready', function () {
var bars = container.getElementsByTagName('path');
Array.prototype.forEach.call(bars, function(bar) {
// reduce width by 50%
bar.setAttribute('transform', 'scale(0.5,1)');
});
});
chart.draw(data, {});
},
packages: ['bar']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I used the following (inspired by #Amaud)
To prevent a bar-chart with one very thick row, I add blank rows using the following code
if (tData.getNumberOfRows()==1) {
addRow(tData,' ',1);
addRow(tData,' ',1);
}
The full code is as follows:
Note that the function addRow adds a row to the chart only if there is a value, therefore sometimes
there can be only one row which ends up being very thick.
var tData = new google.visualization.DataTable();
tData.addColumn('string','Type');
tData.addColumn('number','Amount (Millions)");
addRow(tData,'Row1', a1);
addRow(tData,'Row2', a2);
addRow(tData,'Row3', a3);
addRow(tData,'Row4', a4);
if (tData.getNumberOfRows()==1) {
addRow(tData,' ',1);
addRow(tData,' ',1);
}
var options = {
...
};
var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(tData, options);
function addRow(tData,text,num) {
if (num>0) {
tData.addRow([text,num/1000000]);
}
}

How to prevent popup in ColumnChart

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);

Google charts API set selection choose series to highlight

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();
}

Google Charts Threshold?

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.

Categories