Google charts annotation not showing - javascript

I am using the google charts api to display data from php. I am displaying this information in a material style bar chart (vertical).
I am trying to add annotations to show the values inside the bars however it isn't working.
JavaScript:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawLastPackets);
function drawLastPackets() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Days');
data.addColumn('number', 'Packets Packed');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows(<?php echo json_encode($chartLastPackets); ?>);
var toAdd = ["Day", "Packets Packed", {"role": "annotation"}];
var options = {
legend: {
position: 'none',
},
series: {
0: {color: '#d7a8a8'}
},
vAxis: {
title: 'Packets'
}
};
var chart = new google.charts.Bar(document.getElementById('lastPackets'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
The contents of the php array $chartLastPackets is:
[["Mon", 1, "1"], ["Tue", 3, "3"], ["Wed", 5, "5"], ["Thu", 2, "2"], ["Fri", 0, "0"]]
However all I can see is the chart itself without the annotation.

annotations.* are listed among the several options that don't work on Material charts
you can use the following option, to get the chart close to the look & feel of Material
theme: 'material'
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Days');
data.addColumn('number', 'Packets Packed');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([["Mon", 1, "1"], ["Tue", 3, "3"], ["Wed", 5, "5"], ["Thu", 2, "2"], ["Fri", 0, "0"]]);
var options = {
legend: {
position: 'none',
},
series: {
0: {color: '#d7a8a8'}
},
theme: 'material',
vAxis: {
title: 'Packets'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('lastPackets'));
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="lastPackets"></div>

Related

Google Charts - Plot different things in different parts of the chart

So I'm currently building a financial chart with price information, account balance and an additional technical indicator, my current issue is that whilst displaying price information or account balance is fairly straight forward and non-obstructive, displaying the additional technical indicator puts it in the way of the other information as it is oscillating in value.
This is what I currently have but ideally I'd want the RSI to be at the bottom of the chart like so: (only the position of having the technical indicator at the bototm)
My current code to generate this
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawCurveTypes);
function drawCurveTypes() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Backtest');
data.addColumn('number', 'BTCUSDT');
data.addColumn({ 'type': 'string', 'role': 'style' })
data.addColumn('number', 'RSI');
data.addRows([date, balance, price, null, rsi]);
var options = {
hAxis: {
title: 'Time',
},
vAxes: {
// Adds titles to each axis.
0: { title: 'Price' },
1: { title: 'Backtest' },
2: { title: 'RSI'},
},
series: {
0: { targetAxisIndex: 0 },
1: { targetAxisIndex: 1 },
2: { targetAxisIndex: 2 }
},
explorer: {
axis: 'horizontal',
keepInBounds: true,
maxZoomIn: 20
},
colors: ['#6C91DB', 'black','orange'],
pointSize: 1,
dataOpacity: 0.7
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

Google charts with tooltips and colors

I have seen one post which shows how to make color but it uses a method which is i didnt understand and its little dificult for me. im using this method in fiddle which is easy But it didnt work HTML inside tooltips .
google.charts.load('current', {'packages':['corechart','bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Statistics', 'Amount', { role: 'style' } , { role: 'tooltip' }],
['Categories', 5, '#D9534F' , "<img src='https://upload.wikimedia.org/wikipedia/commons/5/52/Xylocopa_virginica_male_face.jpg' width='40px' height = '40px'/>"],
['Posts', 4, '#337AB7' , 'my tooltip'],
['Comments', 8, '#5CB85C' ,'<div>fff</div>'],
['Users', 3, '#F0AD4E' , '<b>hhh</b>'],
]);
var options = {
chart: {
title: 'Analysis',
tooltip: { isHtml: true},
subtitle: '',
},
/* colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'], // Another coloring method*/
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.visualization.BarChart(document.getElementById('barchart_material'));
chart.draw(data, options);
}
Js Fiddle here
thanks , hope if someone have a question i can edit and add something before votingdown :) .
first, need to understand difference between Classic and Material charts...
Classic = google.visualization.BarChart -- packages: ['corechart']
Material = google.charts.Bar -- packages: ['bar']
Material charts do not support column roles -- {role: 'style'} , {role: 'tooltip'}
next, there are two things needed for html tooltips on a Classic chart...
1) a property on the column must exist -- {role: 'tooltip', p: {html: true}}
2) and the chart option -- tooltip: { isHtml: true}
however, it should not be within the chart option, which is for Material charts only
(remove chart: {})
var options = {
title: 'Analysis',
tooltip: { isHtml: true}
};
see following working snippet...
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Statistics', 'Amount', {role: 'style'} , {role: 'tooltip', p: {html: true}}],
['Categories', 5, '#D9534F' , "<img src='https://upload.wikimedia.org/wikipedia/commons/5/52/Xylocopa_virginica_male_face.jpg' width='40px' height = '40px'/>"],
['Posts', 4, '#337AB7' , 'my tooltip'],
['Comments', 8, '#5CB85C' ,'<div>fff</div>'],
['Users', 3, '#F0AD4E' , '<b>hhh</b>'],
]);
var options = {
title: 'Analysis',
tooltip: { isHtml: true}
};
var chart = new google.visualization.BarChart(document.getElementById('barchart'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barchart"></div>

Moving annotations on Bar Chart with Negative Values Google Chart

I am using google charts within an MVC project.
I am looking to implement a bar chart that has negative values.
I would like the annotations on the negative portion of the chart to be on the same side as the end of the bar (just like the positive, see image below, green box is where I would like annotations to be).
I cant seem to find any documentation on how this can be achieved.
Is it possible to move the annotation to the other side?
there are no standard config options that will move the annotations
but you can move them manually
however, the chart will actually move them back whenever activity occurs,
such as on bar hover
have to use a MutationObserver, or something, to keep them there
use chart methods --> getChartLayoutInterface().getXLocation(value)
to find the location
also, need to adjust the axis window to leave room for the labels
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
],
rows: [
{c:[{v: 'Omega'}, {v: -0.95}]},
{c:[{v: 'Large'}, {v: -0.92}]},
{c:[{v: 'Medium'}, {v: 2.76}]},
{c:[{v: 'Tiny'}, {v: 2.03}]}
]
});
var options = {
annotations: {
alwaysOutside: true,
stem: {
color: 'transparent'
},
textStyle: {
color: '#000000'
}
},
hAxis: {
// leave room for annotation
viewWindow: {
min: data.getColumnRange(1).min - 1
}
},
legend: {
position: 'none'
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var container = document.getElementById('chart');
var chart = new google.visualization.BarChart(container);
// move annotations
var observer = new MutationObserver(function () {
$.each($('text[text-anchor="start"]'), function (index, label) {
var labelValue = parseFloat($(label).text());
// only negative -- and -- not on tooltip
if ((labelValue < 0) && ($(label).attr('font-weight') !== 'bold')) {
var bounds = label.getBBox();
var chartLayout = chart.getChartLayoutInterface();
$(label).attr('x', chartLayout.getXLocation(labelValue) - bounds.width - 8);
}
});
});
observer.observe(container, {
childList: true,
subtree: true
});
chart.draw(view, options);
},
packages: ['corechart']
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Google Charts ColumnChart date format not showing minutes and hours

I'm trying to make a column chat, using Google charts with the numbers up the vertical axis, and dates across the horizontal axis. For some reason the date format does not print the hours, minutes or seconds. It does work just fine with year, month and day.
I'm using the format "M-d, HH:mm:ss" to format and print this timestamp: "2017-07-15 20:10:30" but instead it prints
7-17,00:00:00 instead of 7-17, 20:10:30
Is this a bug or have i missed something?
<html>
<head>
<script src="https://www.google.com/jsapi?ext.js"></script>
</head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Present');
data.addRows([
[new Date("2017-07-15 20:10:30"), 5]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var options = {
width: 600,
height: 400,
//bar: {groupWidth: "95%"},
legend: { position: "none" },
vAxis: {title: 'Times occured'},
hAxis: {
format: "M-d, HH:mm:ss", // <------- This shows: "7-17,00:00:00" not "7-17, 20:10:30"
//format: "HH:mm",
//format:'M-d H:mm',
title: 'Date',
},
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, options);
}
</script>
<body class="chart">
<div id="chart_div"></div>
</body>
</html>
looks like some sort of bug,
recommend using a discrete axis (string) for column charts anyway
you could use a data formatter to convert the x-axis
see following working snippet...
google.charts.load("current", {
callback: drawChart,
packages:["corechart"]
});
function drawChart() {
var formatDate = new google.visualization.DateFormat({
pattern: 'M-d, HH:mm:ss'
});
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Present');
data.addRows([
[new Date("2017-07-15 20:10:30"), 5]
]);
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return formatDate.formatValue(dt.getValue(row, 0))
},
type: "string",
label: data.getColumnLabel(0)
}, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);
var options = {
width: 600,
height: 400,
legend: { position: "none" },
vAxis: {title: 'Times occured'},
hAxis: {
title: 'Date'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Removing Decimals From Line Chart Axis

I have a google line chart I'm using and in many cases the numbers on the axis represent decimals point. Obviously since my data represents people it makes no sense to show the axis in decimal points. I would like for them to rounded up to whole numbers. So far I've been toiling with the format option in the xAxis like so.
var options = {
legend: 'none',
hAxis: {
title: 'Dogs',
format: 'long'
}
};
However, the points on the xAxis are represented as decimals. The jsfiddle can be found here. What's wrong and how can I fix this?
You could set custom format specifiers such as:
# (Digit placeholder)
0 (Zero placeholder)
Example
google.load('visualization', '1', { packages: ['corechart', 'line'] });
google.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
data.addRows([
[0, 0]
]);
var options = {
legend: 'none',
hAxis: {
title: 'Dogs',
format: '#'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Another option is to specify hAxis.ticks:
Replaces the automatically generated X-axis ticks with the specified
array.
Example
google.load('visualization', '1', { packages: ['corechart', 'line'] });
google.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
data.addRows([
[0, 0]
]);
var options = {
legend: 'none',
hAxis: {
title: 'Dogs',
//format: '#'
ticks: [-1,0,1]
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>

Categories

Resources