Google Charts: Data label with suffix - charts

I am just starting with using google charts. I have a question. I would like to add data labels to my columns, in fact I have succeeded in this. However, I would like to add a suffix to these labels (percentages %). I have tried to use NumberFormat, but then no chart appears. What am I doing wrong?
<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([
['Kenmerk', 'Belangrijkheid', { role: 'style' } ],
['Uitstellen', 10, 'color: gray'],
['bijwerkingen', 20, 'color: yellow'],
['behandelingen', 30, 'color: red'],
['Schema', 40, 'color: blue']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
// Set chart options
var options = {
width: 800,
height: 600,
title: 'Uitslag',
vAxis: { title: 'belangrijkheid van elk kenmerk in percentages uitgedrukt', format: '#\'%\'', maxValue: '100', minValue: '0'},
legend: { position: 'none'},
bar: { groupWidth: '75%' },
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script></p>
<div id="columnchart_values" style="width: 800px; height: 600px;">
</div>

Related

Google Charts API Area Chart display only max and min values in annotation

I'm using a Google Charts API Area Chart to display a simple Google Spreadsheet: Column 0 stores dates and Column 1 values. Actually the chart is displaying all values in annotation by default. But I only want to display the min and max value of column 1 in annotation.
I can't find the solution for my problem and maybe you can help me with my sourcecode.
Thanks Mags
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function initialize() {
var opts = {sendMethod: 'auto'};
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/MYSPREADSHEET', opts);
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
var options = {
title: '',
curveType: 'function',
legend: {position: 'none'},
lineWidth: 4,
backgroundColor: '#2E4151',
colors:['white'],
fontSize: '26',
fontName: 'Open Sans',
animation:{
"startup": true,
duration: 800,
easing: 'inAndOut',
},
hAxis: {
gridlines: {color: 'transparent', count: 4},
textStyle: {color: '#FFF'}
},
vAxis: {
gridlines: {color: 'white', count: 5},
viewWindow: {min: 87, max: 101},
textStyle: {
color: '#FFF',
fontSize: 18
},
},
trendlines: {
0: {
type: 'polynomial',
color: 'yellow',
lineWidth: 5,
opacity: 0.7,
showR2: true,
visibleInLegend: true
}
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="chart_div" style="width:100%; height:100%"></div>
</body>
</html>
you can use data table method --> getColumnRange(columnIndex)
this will return an object with the min & max values of the column.
then you can use the calc function on the data view,
to determine if the value matches either the min or max,
and return the formatted value for the annotation.
return null if it does not, see following snippet...
var data = response.getDataTable();
var range = data.getColumnRange(1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: function (dt, row) {
var value = dt.getValue(row, 1);
if ((value === range.min) || (value === range.max)) {
return dt.getFormattedValue(row, 1);
}
return null;
}
}]);

Google Chart - Bar Series Title Different Color

I have a chart which has 4 series (Fiddle link below). Currently, it has Title1, Title2, Title3, and Title4. I want to change the different color for each title text name (Not the bar); for example, Title1 is red, Title2 is blue, Title3 is green, and Title4 is black. Is there a way to change all these titles with different colors?
https://jsfiddle.net/milacay/e4fe4hsz/21/
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test Google Chart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {callback: drawChart, packages: ['corechart']});
function drawChart() {
var array = [
["", "Today", "Goal"],
["Title1", 4553, 4151],
["Title2", 5560, 6150],
["Title3", 850, 920],
["Title4", 10505, 12320]
];
var data = new google.visualization.arrayToDataTable(array);
var formatTooltip = new google.visualization.NumberFormat({
pattern : '#,##0'
});
formatTooltip.format(data, 1);
formatTooltip.format(data, 2);
var formatShort = new google.visualization.NumberFormat({
pattern : 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 1));
},
type : "string",
role : "annotation"
},
2, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 2));
},
type : "string",
role : "annotation"
},
]);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true,
}
},
chartArea: {right:0
, width: "80%"
, height: "80%"
},
bar: {
groupWidth: 55 // Set the width for each bar
},
legend: {position:'top'},
hAxis: {
format: 'short',
//title: 'Month',
textStyle : {
bold: true,
fontSize: 10 // fontsize for the vAxis label.
//color: 'darkblue',
},
},
vAxis: {
format: 'short',
title: 'Progress To-Date',
gridlines: { count: 8 }
},
width:320,
height:300,
bars: 'vertical',
colors: ["lightblue", "lightgray"]
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
if you want to change the color of the axis labels,
change those manually when the chart's 'ready' event fires,
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var array = [
["", "Today", "Goal"],
["Title1", 4553, 4151],
["Title2", 5560, 6150],
["Title3", 850, 920],
["Title4", 10505, 12320]
];
var data = new google.visualization.arrayToDataTable(array);
var formatTooltip = new google.visualization.NumberFormat({
pattern : '#,##0'
});
formatTooltip.format(data, 1);
formatTooltip.format(data, 2);
var formatShort = new google.visualization.NumberFormat({
pattern : 'short'
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 1));
},
type : "string",
role : "annotation"
},
2, {
calc : function (dt, row) {
return formatShort.formatValue(dt.getValue(row, 2));
},
type : "string",
role : "annotation"
},
]);
var options = {
chart: {
title: ' ',
animation: {
duration: 2000,
easing: "out",
startup: true,
}
},
chartArea: {right:0
, width: "80%"
, height: "80%"
},
bar: {
groupWidth: 55 // Set the width for each bar
},
legend: {position:'top'},
hAxis: {
format: 'short',
//title: 'Month',
textStyle : {
bold: true,
fontSize: 10 // fontsize for the vAxis label.
//color: 'darkblue',
},
},
vAxis: {
format: 'short',
title: 'Progress To-Date',
gridlines: { count: 8 }
},
width:320,
height:300,
bars: 'vertical',
colors: ["lightblue", "lightgray"]
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var colorIndex = 0;
var colorPallette = ['red', 'blue', 'green', 'black'];
Array.prototype.forEach.call(container.getElementsByTagName('text'), function (label) {
if ((label.getAttribute('text-anchor') === 'middle') && (label.getAttribute('fill') !== '#404040')) {
label.setAttribute('fill', colorPallette[colorIndex]);
colorIndex++;
}
});
});
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: the label color (#404040) is used to differentiate the x-axis labels from the annotation labels...

Google Charts focusTarget: 'category' not working

Google Charts focusTarget: 'category' works when I draw the chart in one way but not in the other one.
In the example below, the BAR I has a broken tooltip (not triggering the way intended) and it's working perfectly fine with the BAR II
google.charts.load('current', {
'packages': ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// _____ BAR I ______
var data = google.visualization.arrayToDataTable([
['Form', 'Visitors', 'Starters', 'Conversions'],
['Form 1', 1000, 650, 490],
['Form 2', 485, 460, 350],
['Form 3', 335, 250, 105]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
focusTarget: 'category',
},
focusTarget: 'category',
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
// ______ BAR II ______
var data = google.visualization.arrayToDataTable([
['Form', 'Visitors', 'Starters', 'Conversions'],
['Form 1', 1000, 650, 490],
['Form 2', 485, 460, 350],
['Form 3', 335, 250, 105]
]);
var options = {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
// This line makes the entire category's tooltip active.
focusTarget: 'category',
// Use an HTML tooltip.
tooltip: {
isHtml: true
}
};
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('columnchart_material_2')).draw(data, options);
}
Please also take a look at this JSFiddle of the problem.
Besides different tooltip behavior, the charts also look rather different, what is the cause?
one is considered a Classic chart, the other Material
Classic --> google.visualization.ColumnChart -- requires package: 'corechart'
Material --> google.charts.Bar -- requires package: 'bar'
Material charts are newer, but also do not support several options...
see --> Tracking Issue for Material Chart Feature Parity
which includes...
focusTarget
there is an option for Classic charts, to style them similar to Material
theme: 'material'
Here is the codepen link for using google charts
google.charts.load('visualization', '1', {
'packages': ['corechart'],
"callback": drawChart
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Year", "Relevance", {
role: "style"
}],
["Forward ref..", 108, "#25C16F"],
["Case ref..", 20, "#25C16F"],
["Approved", 30, "#25C16F"],
["Disapproved", 50, "#25C16F"],
["Distinguish", 25.67, "#25C16F"],
["Followed", 28.9, "color: #25C16F"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
var options = {
title: "Case Relevance",
width: 350,
height: 300,
bar: {
groupWidth: "50%",
},
hAxis: {
title: 'Relevance',
viewWindow: {
min: 0,
max: 120
},
ticks: [0, 30, 60, 90, 120] // display labels every 25
},
legend: {
position: "none"
},
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(vieenter code herew, options);
google.visualization.events.addListener(chart, 'select', function() {
var row = chart.getSelection()[0].row;
if (row == 0) {
$("#right_panel h2").children(".small-font").html("Forward Reference in");
} else if (row == 1) {
$("#right_panel h2").children(".small-font").html("Case Reference");
} else if (row == 2) {
$("#right_panel h2").children(".small-font").html("Approved");
} else if (row == 3) {
$("#right_panel h2").children(".small-font").html("Disapproved");
} else if (row == 4) {
$("#right_panel h2").children(".small-font").html("Distinguish");
} else if (row == 5) {
$("#right_panel h2").children(".small-font").html("Followed");
}
});
}
});
https://codepen.io/shray04/pen/Poogmjq?editors=1000

Material design google charts change color column

When using Google charts, usually you can change the colors of individual columns by using the "role: style" function, but when I attempt it with the new material design charts I only get blue columns.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['', '', { role: 'style' } ],
["Strongly disagree", 0, 'color: black'],
["Disagree", 0, 'color: #000000'],
["Neutral", 6, 'color: #212121'],
["Agree", 45, 'color: #212121'],
['Stongly agree', 98, 'color: black']
]);
var options = {
title: 'Instructor presented the subject matter clearly',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'General physics 221 CSUSB winter 2017' },
axes: {
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
You can try with netx code:
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawColColors);
function drawColColors() {
var data = new google.visualization.arrayToDataTable([
['', '', { role: 'style' } ],
["Strongly disagree", 12, 'brown'],
["Disagree", 30, 'gray'],
["Neutral", 26, 'blue'],
["Agree", 45, 'color: #F05921'],
['Stongly agree', 58, 'black']
]);
var options = {
title: 'Instructor presented the subject matter clearly',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'General physics 221 CSUSB winter 2017' },
axes: {
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('chart_div'));
// Convert the Classic options to Material options.
//chart.draw(data, google.charts.Bar.convertOptions(options));
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Visualization API -- Putting Y Axis on Right Side?

Using: http://code.google.com/apis/chart/interactive/docs/gallery/linechart.html#Loading
There isn't any options to put the y axis on the right side of the chart? For reals?! :P
Anyone know how to do such a 'radical' thing? The charting API lets you do this, but not the visualization?
Thanks SO.
You can get around this via the series option, and specifying a dummy data series for series[0]. Like so:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'xAxis');
data.addColumn('number', 'dummySeries');
data.addColumn('number', 'realSeries');
data.addRow(['x label', null, 2]); // dummy series value needs to be null, otherwise if interactivity is on, the user can discover the dummy values even if the line is hidden per below
data.addRow(...iterate & add the rest of your data);
new google.visualization.LineChart(document.getElementById('graphdiv')).
draw(data, {curveType: 'function',
series:[{lineWidth:0},{targetAxisIndex:1}]} // specify right y-axis for 2nd series, and 'hide' the line for the 1st series as a precaution with lineWidth
);
}
google.setOnLoadCallback(drawVisualization);
</script>
function singleUserChart() {
google.charts.load('current', { packages: ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawAnnotations);
function drawAnnotations() {
var dataPercentage = new google.visualization.DataTable();
dataPercentage.addColumn('string', 'Productivity');
dataPercentage.addColumn('number', 'Ravi');
dataPercentage.addColumn({ type: 'string', role: 'annotation' });
dataPercentage.addColumn('number', 'Avg Data');
dataPercentage.addColumn({ type: 'string', role: 'annotation' });
dataPercentage.addRows([
['%Score1', 12, '12%', 15, '15%'],
['%Score2', 25, '25%', 21, '21%']
]);
singleUserChartOptions(dataPercentage, 'individualUserPercentageChart', true, 450);
}
}
function singleUserChartOptions(chartData, chartDivId, isShowPercent, chartWidth) {
var options = {
annotations: {
alwaysOutside: true,
textStyle: {
fontSize: 15,
color: '#000',
auraColor: 'none'
}
},
vAxis: { format: (isShowPercent == true) ? '#\'%\'' : '', ticks :[0,10,20,30,40,50]},
hAxis: {
slantedText: true,
slantedTextAngle: -45,
textStyle: { fontSize: 11 }
},
series: {
0: { targetAxisIndex: 0, },
1: { targetAxisIndex: 1, }
},
vAxes: {
0: { textPosition: 'none' },
1: {}
},
legend: { position: 'top' },
width: chartWidth,
height: 400
};
var chart = new google.visualization.ColumnChart(document.getElementById(chartDivId));
chart.draw(chartData, options);
}
singleUserChart();
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="individualUserPercentageChart" style="height: 500px; width: 100%"></div>
</body>
</html>