Add labels for point in google charts - charts

Does google charts support the ability to add labels to a chart? I need to add labels to the chart, but I don't know how to do it.
I'm using such function for chart draw:
function drawChart(node, rows) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Index');
data.addRows(rows);
var options = {
titleTextStyle: {
color: '#00FF00',
},
height: 350,
width: $('#' + node).width(),
pointsVisible: true,
colors:['#00FF00'],
backgroundColor: '#1b1b1b',
legend: {position: 'right', textStyle: {color: '#fff', fontSize: 12}},
pointShape: 'square',
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 18,
bold: true,
italic: true,
color: '#e5d385',
},
stem: {
length: 0
}
},
hAxis: {
title: "Date",
titleTextStyle: {
color: '#fff'
},
format: 'dd.MM.yyyy',
gridlines: {count: 15, color: '#7d7d7d'},
baselineColor: '#fff',
slantedTextAngle: 45,
slantedText: true,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'},
ticks: ticksX
},
vAxis: {
title: "Index",
titleTextStyle: {
color: '#fff'
},
gridlines: {color: '#7d7d7d'},
minValue: 0,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'},
ticks: ticksY
},
};
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function(data, row) {
var colorDown = '#FF0000';
var colorUp = '#00FF00';
if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
return colorDown;
} else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
return colorDown;
}
return colorUp;
},
type: 'string',
role: 'style',
}
]);
var chart = new google.visualization.LineChart(document.getElementById(node));
chart.draw(dataView, options);
}
I can't find information how to add labels to a chart. All documentation contains information how to add labels to the axes of the chart. I need to add labels above the line chart points.
Can you help me with it?

annotations, or labels, are added using an annotation column role,
similar to the style column role, already being used.
here, I add an annotation column role to the data view,
to display labels for the min & max values...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var rows = [];
var oneDay = (24 * 60 * 60 * 1000);
var currentEndDate = new Date();
var currentStartDate = new Date(currentEndDate.getTime() - (oneDay * 365.25));
for (var i = currentStartDate.getTime(); i <= currentEndDate.getTime(); i = i + oneDay) {
var direction = (i % 2 === 0) ? 1 : -1;
var rowDate = new Date(i);
rows.push([rowDate, rowDate.getMonth() + (rowDate.getDate() * direction)]);
}
drawChart('chart_div', rows);
});
function drawChart(node, rows) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Index');
data.addRows(rows);
var options = {
titleTextStyle: {
color: '#00FF00',
},
height: 350,
width: $('#' + node).width(),
pointsVisible: true,
colors:['#00FF00'],
backgroundColor: '#1b1b1b',
legend: {position: 'right', textStyle: {color: '#fff', fontSize: 12}},
pointShape: 'square',
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 18,
bold: true,
italic: true,
color: '#e5d385',
},
stem: {
length: 0
}
},
hAxis: {
title: "Date",
titleTextStyle: {
color: '#fff'
},
format: 'dd.MM.yyyy',
gridlines: {count: 15, color: '#7d7d7d'},
baselineColor: '#fff',
slantedTextAngle: 45,
slantedText: true,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'}
},
vAxis: {
title: "Index",
titleTextStyle: {
color: '#fff'
},
gridlines: {color: '#7d7d7d'},
minValue: 0,
baselineColor: '#fff',
minorGridlines:{
color: "#494949"
},
textStyle:{color: '#FFF'}
},
};
var range = data.getColumnRange(1);
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// reference existing columns by index
0, 1,
// add function for line color
{
calc: function(data, row) {
var colorDown = '#FF0000';
var colorUp = '#00FF00';
if ((row === 0) && (data.getValue(row, 1) < data.getValue(row + 1, 1))) {
return colorDown;
} else if ((row > 0) && (data.getValue(row - 1, 1) < data.getValue(row, 1))) {
return colorDown;
}
return colorUp;
},
type: 'string',
role: 'style',
},
// add annotation
{
calc: function(data, row) {
var value = data.getValue(row, 1);
if (value === range.min) {
return 'Min: ' + data.getFormattedValue(row, 1);
} else if (value === range.max) {
return 'Max: ' + data.getFormattedValue(row, 1);
}
return null;
},
type: 'string',
role: 'annotation',
}
]);
var chart = new google.visualization.LineChart(document.getElementById(node));
chart.draw(dataView, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://www.gstatic.com/charts/loader.js'></script>
<div id="chart_div"></div>

Related

How to put vertical lines on google chart scatter

How I can make vertical lines on a scatter google chart?
I need to put the red line vertically:
here is my current code:
//making array with data
var dataArray = [];
dataArray.push(["", "", { role: 'annotation' }, "", ""]);
projects.forEach(function(item, index){
dataArray.push([parseFloat(item["bottomData"]), parseFloat((item["leftData"])), index+1, 10, 15]);
});
var data = google.visualization.arrayToDataTable(dataArray);
//define ticks
var rangeX = data.getColumnRange(0);
var ticksX = [];
for (var i = (Math.floor(rangeX.min / 5) * 5); i <= (Math.ceil(rangeX.max / 5) * 5); i = i + 5) {
ticksX.push(i);
}
var rangeY = data.getColumnRange(1);
var ticksY = [];
for (var i =(Math.floor(rangeY.min/5) * 5); i <= Math.ceil(rangeY.max/5) * 5; i=i+5) {
ticksY.push(i);
}
//define options
var options = {
series: {
1: {
lineWidth: 2,
pointSize: 0,
color: 'green'
},
2: {
lineWidth: 2,
pointSize: 0,
color: 'red'
},
},
colors:['002060'],
vAxis: {
ticks: ticksY,
},
hAxis: {
ticks: ticksX,
},
};
//print chart
var chart = new google.visualization.ScatterChart(document.getElementById("chartDiv"));
chart.draw(data, options);
I also tried using multiple axes putting some with direction=-1 or orientation=vertical but it doesn't work
in order to mix line series with scatter,
you will need to use a ComboChart
and to get vertical lines,
you will need to add multiple rows with the same x axis value,
with values for the min and max y axis values.
in the options, set the seriesType to 'scatter'
and change the series type to 'line'
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['x', 'y0', {role: 'annotation', type: 'number'}],
[26, 1, 1],
[33, 5, 2],
[36, 1, 3],
[38, 6, 4],
[58, 1, 5]
]);
var ticksX = [25, 30, 35, 40, 45, 50, 55, 60];
var ticksY = [0, 5, 10, 15, 20, 25];
data.addColumn('number', 'y1');
data.addColumn('number', 'y2');
//red line (vertical)
ticksY.forEach(function (value) {
data.addRow([40, null, null, null, value]);
});
//green line (horizontal)
ticksX.forEach(function (value) {
data.addRow([value, null, null, 10, null]);
});
data.sort([{column: 0}]);
var options = {
interpolateNulls: true,
seriesType: 'scatter',
series: {
1: {
color: 'green',
type: 'line'
},
2: {
color: 'red',
type: 'line'
},
},
colors:['002060'],
vAxis: {
ticks: ticksY
},
hAxis: {
ticks: ticksX
},
};
var chart = new google.visualization.ComboChart(document.getElementById("chartDiv"));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chartDiv"></div>

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 Charts - Apply margin on y-axis values

What I'd like to do, is to increase the margin between the y-axis values and the corresponding bar within the chart.
So if I have a bar in the chart which has a value of "Python" on the Y- axis, I want to increase the space between the string "Python" and the visual bar.
Now:
Python__========================================================
My goal:
Python___________=========================================================
___ represents the space between y-axis label and visual bar
I tried to use chartArea{right:200} and textPosition:out in the options section of the chart.
var options = {
chartArea:{right: 200},
'vAxis': {
title:'',
textStyle : {
fontSize: 25
},
textPosition: 'out'
},
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Coding-Skills', 'Skill-Level'],
['C', {v: 0.3, f:'low'}],
['Python', {v: 1, f:'medium'}],
['Javascript', {v: 1.5, f:'medium'}],
['HTML/CSS', {v: 1.5, f:'medium'} ]
]);
var options = {
chartArea: {
left: 1400
},
'hAxis': {
gridlines:{
count: 0},
textStyle : {
fontSize: 25
}
},
'vAxis': {
title:'',
textStyle : {
fontSize: 25
}
},
chart: {
},
bars: 'horizontal',
axes: {
x: {
0: { side: 'bottom', label: 'Years of experience'} ,
textStyle : {
fontSize: 35
}
}
}
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
Applying margin-right
no options for label margins,
but you can move them manually on the chart's 'ready' event
find the labels and change the 'x' attribute
see following working snippet,
here, the chartArea option is used to ensure there is enough room...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Language', 'Skill-Level'],
['C', 20],
['Python', 35],
['Javascript', 50]
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
// move axis labels
if (label.getAttribute('text-anchor') === 'end') {
var xCoord = parseFloat(label.getAttribute('x'));
label.setAttribute('x', xCoord - 20);
}
});
});
var options = {
chartArea: {
left: 100,
right: 200
},
colors: ['#aaaaaa'],
hAxis: {
baselineColor: 'transparent',
gridlines: {
count: 0
},
textStyle: {
color: '#aaaaaa'
}
},
height: 400,
legend: {
textStyle: {
color: '#aaaaaa'
}
},
vAxis: {
textStyle: {
color: '#aaaaaa'
}
}
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Quick addition to existing answer:
$('.transactionValuationChart text').each(function(){
if( $(this).attr('text-anchor') == 'middle' ){
$(this).attr('y', parseFloat($(this).attr('y')) + 20 );
}else{
$(this).attr('x', parseFloat($(this).attr('x')) - 20 );
console.log("left");
}
});
This is a jQuery example which adds 20px of spacing to both x & y axis

google charts dataView format differently from the dataSource?

I've created a dataView in order to put a label on my Google bar chart like :
options = {
title: arr[0][0],
titleTextStyle: { fontSize: '12', color: '#666' },
colors: ['#50c0ed'],
backgroundColor: { fill: 'transparent' },
height: 220,
width: '100%',
is3D: true,
fontSize: '11',
hAxis: { format: '$###,###,###.00' },
vAxis: {
format: '$###,###,###.##',
viewWindow: {
min: 0
}
},
chartArea: { width: '100%', height: '60%', top: '40', left: '65', right: '10' },
tooltip: { textStyle: { color: '#333', fontSize: '11' } }
};
formatter = new google.visualization.NumberFormat({ pattern: '$###,###.##/SF/year' });
formatter.format(data, 1);`enter code here`
view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation",
}]);
chart = new google.visualization.ColumnChart(container[0]);
and the result is enter image description here , but i want to exclude from the label the /SF/year ending but still keep it when i hoover over the bar ,
I tried to set formatter only after i initialize the dataVIew but this doesen't work , Is there i way i can remove /SF/year from the label but keep it when i hoover over ?
use another formatter without --> /SF/year
formatterNumberOnly = new google.visualization.NumberFormat({ pattern: '$###,###.##' });
then in view, use custom calc function instead of "stringify"
use formatValue method to format the value of each row
view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return formatterNumberOnly.formatValue(dt.getValue(row, 1));
},
type: "string",
role: "annotation",
}]);

Different colors for annotations in google charts

I have two types of annotations, one has links and other doesn't. I want to color them both in different colors. Is it possible?
type 1 is -
{
v: 'sample',
Link: 'some link
}
type 2 is -
{
v: 'sample',
}
I want to color type1 in some color and type2 in other, is it possible ?
you can style the annotations for the overall chart,
or for each series individually
see following working snippet,
the fontSize is set to 10 for all annotations
then the colors are changed for the individual series
google.charts.load('current', {
callback: drawStacked,
packages: ['corechart']
});
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Month', 'A', {role: 'annotation'}, 'B', {role: 'annotation'}],
['Aug', 3754, '3,754', 2089, '2,089'],
['Sept', 900, '900', 200, '200'],
['Oct', 2000, '2,000', 4900, '4,900'],
['Nov', 1700, '1,700', 2200, '2,200'],
['Dec', 2400, '2,400', 2089, '2,089']
]);
var options = {
annotations: {
textStyle: {
fontSize: 10
}
},
series: {
0: {
annotations: {
stem: {
color: 'cyan',
length: 5
},
textStyle: {
color: 'cyan'
}
}
},
1: {
annotations: {
stem: {
color: 'magenta',
length: 10
},
textStyle: {
color: 'magenta'
}
}
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
to have different colors for annotations in a single series,
need to change color manually when the 'ready' event fires
see following working snippet...
google.charts.load('current', {
callback: drawStacked,
packages: ['corechart']
});
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Month', 'A', {role: 'annotation'}],
['Aug', 3754, '3,754'],
['Sept', {v: 900, p: {link: 'type A'}}, '900'],
['Oct', {v: 2000, p: {link: 'type B'}}, '2,000'],
['Nov', 1700, '1,700'],
['Dec', 2400, '2,400']
]);
var options = {
annotations: {
textStyle: {
color: '#000000',
fontSize: 10
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
Array.prototype.forEach.call(container.getElementsByTagName('text'), function (text, index) {
for (var i = 0; i < data.getNumberOfRows(); i++) {
if ((text.getAttribute('text-anchor') === 'middle') && (text.innerHTML === data.getFormattedValue(i, 1))) {
switch (data.getProperty(i, 1, 'link')) {
case 'type A':
text.setAttribute('fill', 'magenta');
break;
case 'type B':
text.setAttribute('fill', 'cyan');
break;
}
}
}
});
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>