Change color of a bar in google columnchart - google-visualization

I am using columnchart to generate a chart . Below is the code:
function drawActiveJobsChart() {
var i=0;
var j=0;
var data = new google.visualization.DataTable();
data.addColumn('string','Systems');
data.addColumn('number', 'Counts');
$.getJSON('SubSystemNumbers.action', function(json) {
$.each( json.SysActNum, function( key, val ) {
i++;
});
data.addRows(i);
$.each( json.SysActNum, function( key, val ) {
if (val>=30) {
data.setProperty(j,1,'style','color:red');
}
data.setValue(j, 0,key);
data.setValue(j, 1,val);
j++;
});
});
var options = {
title: 'System Numbers',
width:900, height:400,
allowHtml: true,
hAxis: {title: 'Systems', titleTextStyle: {color: 'red'},textStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById(chartDiv));
chart.draw(data, options);
}
Now i have added logic to change the bar color to red when return val is greater than 30 . I tried running in debug and code is executing fine but bar is not showing in red . Please suggest ! Help is appreciated

Setting the "style" property of a cell is not going to change the color of a bar, you need to add a "style" role column to your DataTable:
var data = new google.visualization.DataTable();
data.addColumn('string','Systems');
data.addColumn('number', 'Counts');
data.addColumn({type: 'string', role: 'style'});
and add the style information to this column:
$.getJSON('SubSystemNumbers.action', function(json) {
$.each( json.SysActNum, function( key, val ) {
var style = (val >= 30) ? 'color: red' : null;
data.addRow([key, val, style]);
});
});
see working example based on your code here: http://jsfiddle.net/asgallant/dGYs7/

Just in case somebody else runs in to the same issue as me:
I had a similar problem where I couldn't change the color of specific bars in a bar-chart. I did as the documentation said, and tried the answer here by asgallant, but nothing worked.
Turned out, I just needed to change google.charts.Bar to google.visualization.ColumnChart.

Related

How to give api count and date value to google line chart?

I am making a simple web counter using count api. I am good in getting the counts. Now, I'm making a google line chart to show count value with the date in graph form. So, please help me how to set the date and count data in drawChart() function to get the count as per the date. And the graph should have 5 days of count. How to achieve this solution. Sincere Thanks in Advance!
const counter = document.getElementById('count');
updateVisitCount();
function updateVisitCount() {
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
counter.innerHTML = res.value;
});
}
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Number of Site Visits'],
]);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
That's working.
var counters=[
['string', 'value'],
];
setInterval(()=>{
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
var dt = new Date();
var secs = dt.getSeconds()
counters.push(
[secs,res.value]
)
if(counters.length>3){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
}
});
},1000);
function drawChart() {
var data = new google.visualization.arrayToDataTable(counters);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Google charts error:every row given must be either null or an array

I am working on a website that is intended to show some basic Google charts. The data comes from a text file that i retrieve through Ajax. It's got a x, y value and an annotation field. The data looks like this:
[[-0.8, -0.47, "100-005-10"],
[-0.7, -0.46, "100-005-9"],
[-0.6, -0.45, "100-005-8"],
[-0.5, -0.44, "100-005-7"]]
Here's my code:
<script >
var xmlhttp = new XMLHttpRequest();
var array;
xmlhttp.onreadystatechange = function() {
array = this.responseText;
};
xmlhttp.open("GET", "array.array", true);
xmlhttp.send();
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($.parseJSON(array), true)
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn({type: 'string', role: 'annotation'});
data.addRow(array);
var options = {
legend: 'none',
colors: ['#087037'],
selectionMode: 'single',
tooltip: {trigger: 'selection'},
pointSize: 12,
animation: {
duration: 200,
easing: 'inAndOut',
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('animatedshapes_div'));
chart.draw(data, options);
}
</script>
When i run the code, i get this error message:
Error: If argument is given to addRow, it must be an array, or null
I just don't know how to transform the plain text from the ajax response to an array.
try using JSON.parse to convert the string to an actual array...
data.addRows(JSON.parse(array));
In one of the case, need to add Square brackets []
self.tableValues.forEach((row: any) => {
if(row) {
dataTable.addRows([row]); // <-- row is array; so try [row]
}
});

Google Chart - Centering Annotations

I simply want to "center" the annotation in the bars in this chart. You can see how the data appear at the end of the bar. Can that percentage be centered in the bar?
Try as I might, I cannot figure it out. I found a block of code that was described as a hack, but it would have to be customized for each chart. I use this code to generates lots and lots of charts. Any help would be wildy appreciated!
function drawVisualizationstack(qid,cdata, w,h,l,cw,pos,stacked,questioncase) {
pos='top';
var data = new google.visualization.DataTable();
var e;
for (var k=0;k<cdata.length;k++) {
e=cdata[k];
if (e[0]=='column') {
if (e[2]=="tooltip") {
data.addColumn({type:'string',role:'tooltip','p':{'html':true}});
//data.addColumn({type: 'string', role: 'annotation','p':{'html':true}});
}
else if (e[2]=="annotation") {
data.addColumn({type: 'string', role: 'annotation', p: {html: true}});
}
else {
if (e[2]=="All") e['2']="All";
data.addColumn(e[1],e[2]);
}
}
else {
if (e==="" || e===undefined) {mclog('UNDEFINED DATA ROW FOR ' + qid);}
else {
data.addRow(e);
}
}
}
h=h*.75;
var chartHeight=h-65;
var options = {
width:500,
height:h,
isStacked:true,
chartArea:{height:chartHeight,left:l,width:cw},
backgroundColor:'transparent',
bar:{groupWidth:'80%'},
tooltip: {isHtml:true},
legend:{position:'none'},
hAxis: {title: 'Percentage',minValue:0,maxValue:100},
hAxis: {textPosition: 'none',ticks: [0]},
colors: ['#5d5d5d', '#002e32', '#0e1a40', '#364940', '#a9b861', '#404000', '#504000', '#604000', '#003070', '#687000'] //set default colors for charts
}}},
true,italic: true,color: '#871b47',auraColor: '#d799ae',opacity: 0.8}}
}
var chart = new google.visualization.BarChart(document.getElementById('questchart_'+qid));
jQuery("base").attr('href',document.location);
chart.draw(data,options);
}

Google Line Chart Legend Click Events

I want to hide the line in Line chart when ever the user clicks on the Line Chart legend. Is there any way that I can do it in Google Chart API ? I seen this feature on Highcharts.
Yes it is possible. Here is an example by asgallant:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'City');
data.addColumn('number', 'Foo');
data.addColumn('number', 'Foo');
data.addColumn('number', 'Bar');
data.addColumn('number', 'Bar');
data.addColumn('number', 'Baz');
data.addColumn('number', 'Baz');
data.addRow(['Boston', 5, null, 7, null, 2, null]);
data.addRow(['New York', 4, null, 8, null, 5, null]);
data.addRow(['Baltimore', 6, null, 2, null, 4, null]);
/* define the series object
* follows the standard 'series' option parameters, except it has two additonal parameters:
* hidden: true if the column is currently hidden
* altColor: changes the color of the legend entry (used to grey out hidden entries)
*/
var series = {
0: {
hidden: false,
visibleInLegend: false,
color: '#FF0000'
},
1: {
hidden: false,
color: '#FF0000',
altColor: '#808080'
},
2: {
hidden: false,
visibleInLegend: false,
color: '#00FF00'
},
3: {
hidden: false,
color: '#00FF00',
altColor: '#808080'
},
4: {
hidden: false,
visibleInLegend: false,
color: '#0000FF'
},
5: {
hidden: false,
color: '#0000FF',
altColor: '#808080'
}
};
var options = {
series: series,
height: 400,
width: 600
};
var view = new google.visualization.DataView(data);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'select', function () {
// if row is undefined, we clicked on the legend
if (typeof chart.getSelection()[0]['row'] === 'undefined') {
// column is the DataView column, not DataTable column
// so translate and subtract 1 to get the series index
var col = view.getTableColumnIndex(chart.getSelection()[0]['column']) - 1;
// toggle the selected column's data counterpart visibility
series[col - 1].hidden = !series[col - 1].hidden;
// swap colors
var tmpColor = series[col].color;
series[col].color = series[col].altColor;
series[col].altColor = tmpColor;
// reset the view's columns
view.setColumns([0,1,2,3,4,5,6]);
// build list of hidden columns and series options
var hiddenCols = [];
options.series = [];
for (var i = 0; i < 6; i++) {
if (series[i].hidden) {
// add 1 to the series index to get DataTable column
hiddenCols.push(i + 1);
}
else {
options.series.push(series[i]);
}
}
// hide the columns and draw the chart
view.hideColumns(hiddenCols);
chart.draw(view, options);
}
});
chart.draw(view, options);
}
Here is the solution. You can hide line in your line chart by clicking the legend.
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (typeof sel[0].row === 'undefined') {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
Here is the working sample. jqfaq.com
As mentioned above, you can create a DataView for your DataTable and then
to show only the clicked line/column, call
view.setColumns(chart.getSelection()[0].column)
to hide the clicked line/column call
view.hideColumns(chart.getSelection()[0].column)
getSelection() will have the line/legend on the chart you have selected.

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}