Archive for category Google Charts

Hiding zero-value items in Google Charts

Working with Google Charts, I had three values I was putting into a bar chart. There were times when some of the values would be zero, and I didn’t want them to show. Usually, they didn’t, but once in a while, a sliver of red would peak through, as you can see in the image:

Google Charts

Google Charts

To get around this, I explicitly set the value in question to null instead of zero. So in my loop where I bind the data to the chart, I check to see if the value is zero. I’ve included the entire function for continuity. The variable “finalData” is a class passed from a Web API call, and the Foods is a generic List of class Food, which has four properties: Name, Ate, Eating, and WillEat:

function renderChart(finalData) {
var data = new google.visualization.DataTable();

data.addColumn(‘string’, ‘Text’);
data.addColumn(‘number’, ‘Ate’);
data.addColumn({ ‘type’: ‘string’, ‘role’: ‘tooltip’, ‘p’: { ‘html’: true } })
data.addColumn(‘number’, ‘Eating’);
data.addColumn({ ‘type’: ‘string’, ‘role’: ‘tooltip’, ‘p’: { ‘html’: true } })
data.addColumn(‘number’, ‘Will Eat’);
data.addColumn({ ‘type’: ‘string’, ‘role’: ‘tooltip’, ‘p’: { ‘html’: true } })
data.addColumn({ type: ‘string’, role: ‘annotation’ });

data.addRows(finalData.Foods.length);

for (var i = 0; i < finalData.Foods.length; i++) {

if (finalData.Foods[i] != null && finalData.Foods[i].Eating== 0) {
finalData.Foods[i].Eating= null;
}

data.setValue(i, 0, finalData.Foods[i].Name);
data.setValue(i, 1, finalData.Foods[i].Ate);
data.setValue(i, 2, ‘<p style=”font-size: 12; text-align: center; vertical-align: middle”>Ate</p>’);
data.setValue(i, 3, finalData.Foods[i].Eating);
data.setValue(i, 4, ‘<p style=”font-size: 12; text-align: center; vertical-align: middle”>Eating</p>’);
data.setValue(i, 5, finalData.Foods[i].WillEat);
data.setValue(i, 6, ‘<p style=”font-size: 12; text-align: center; vertical-align: middle”>Will Eat</p>’);
data.setValue(i, 7, ”);
}

var options = {
title: ‘Favorite Foods’,
titleTextStyle: { ‘fontSize’: 22 },
fontSize: 12,
width: 570,
height: 275,
legend: { position: ‘none’ },
isStacked: true,
tooltip: { isHtml: true, textStyle: { fontName: ‘Arial’, fontSize: 16 } },
series: {
0: { color: ‘green’ },
1: { color: ‘red’ },
2: { color: ‘blue’ },
}
};

var chart = new google.visualization.BarChart(document.getElementById(‘chartDiv’));
chart.draw(data, options);
}

Leave a comment