Column data label on google bar chart - google-visualization

I am trying to add a column data label to a google bar chart.
I have followed the instructions given in the API docs, and this is what I get:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Searches'],
['1998', 9800],
['2000', 60000000],
['2007', 1200000000],
['2008', 1745000000],
['2009', 2610000000],
['2010', 3627000000],
['2011', 4717000000],
['2012', 5134000000],
['2013', 5922000000],
['2014', 5740000000]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" }]);
var options = {
chart: {
title: 'Google searches',
subtitle: 'Average searches per day 1998-2014',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(view, options);
}
I must be doing something wrong as the chart fails to render any data labels.
What am I doing wrong?
https://jsfiddle.net/q9edfpte/1/

I did a number of changes*, and this one ultimately worked.
*Changes:
- 'packages':['bar'] --> 'packages':['corechart']
- google.charts.Bar --> google.visualization.ColumnChart
Working version (though needs beautifying):
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Searches'],
['1998', 9800],
['2000', 60000000],
['2007', 1200000000],
['2008', 1745000000],
['2009', 2610000000],
['2010', 3627000000],
['2011', 4717000000],
['2012', 5134000000],
['2013', 5922000000],
['2014', 5740000000]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" }]);
var options = {
title: 'Google searches',
subtitle: 'Average searches per day 1998-2014',
};
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart_values'));
chart.draw(view, options);
}

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 Bar Chart custom tooltip does not work

This code:
chart = new google.charts.Bar(document.getElementById('chart'));
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', '');
dataTable.addColumn('number', 'Value');
dataTable.addColumn({type: 'string', role: 'tooltip', p: {'html': true}});
var rows = [
['U.S.', 2, "tool"],
['France', 10, "tip"]
];
dataTable.addRows(rows);
chart.draw(dataTable);
does not result in a custom tooltip.
Strangely it works with other chart types.
Do you know why please?
[edit] Apparently this is not possible. Is there any other way to put a "%" symbol in the tooltip, like in this screenshot?
The tooltip should show the formatted value by default.
Using object notation for your values, you can provide a formatted value (f:)
along with the required value (v:)...
you can also use dataTable.setFormattedValue(...) after the table is loaded...
Example...
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
function drawChart() {
chart = new google.charts.Bar(document.getElementById('chart'));
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', '');
dataTable.addColumn('number', 'Value');
var rows = [
['U.S.', {v: 2, f: '2%'}], // add %
['France', {v: 10, f: '10%'}], // add %
['Germany', {v: 15, f: 'whatever we want'}] // add whatever we want
];
dataTable.addRows(rows);
chart.draw(dataTable);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Use column as metadata in Google Charts

Given the following data (from Google Charts example page):
var data = ['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
How can I render just a line chart that shows sales, but on hover I get this tooltip?
2006
Sales: 660
Expenses: 540
Here is the jsbin:
http://jsbin.com/fefod/1/edit?html,js,output
Essentially I would like to use the third column as extra data for that specific data point, rather than a whole new series. I've read that I cold use "annotation" columns but unsure how I could use them. Thanks in advance.
The way to achieve what you want is to use custom tooltips. You can create a DataView that constructs these automatically for you, eg:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
tooltip: {
isHtml: true
}
};
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'tooltip',
properties: {
html: true
},
calc: function (dt, row) {
var year = dt.getFormattedValue(row, 0),
sales = dt.getFormattedValue(row, 1),
expenses = dt.getFormattedValue(row, 2);
return '<div class="tooltip"><span class="tooltipHeader">Year</span>: ' + year + '<br /><span class="tooltipHeader">Sales</span>: ' + sales + '<br /><span class="tooltipHeader">Expenses</span>: ' + expenses + '</div>';
}
}]);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(view, options);
}
You can use any HTML you want in the tooltips, and you'll probably want to style them as well to pretty them up.
As an alternative solution, you can draw the chart with both series, but set the options to hide the second one. Then you can set the focusTarget option to 'category' to show both series in the tooltips at the same time:
series: {
1: {
// hide this series
pointSize: 0,
lineWidth: 0,
displayInLegend: false
}
},
focusTarget: 'category'
Multiple data selections can be rolled up into tooltips using 'aggregationtarget'
an example is given below
var options = {
// Allow multiple simultaneous selections.
selectionMode: 'multiple',
// Trigger tooltips on selections.
tooltip: { trigger: 'selection' },
// Group selections by x-value.
aggregationTarget: 'category',
};
More details: https://developers.google.com/chart/interactive/docs/gallery/linechart#Configuration_Options

Google Charts - interpolateNulls option not working for AnnotationChart

I'm a beginner with Google Visualizations. I'm having trouble with getting the "interpolateNulls: true" option working correctly with an AnnotationChart. If I use the same datasets with a basic LineChart, it works as expected. Here is my code and resulting charts:
<script type='text/javascript'>
google.load('visualization', '1.1', {'packages':['Annotationchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = new google.visualization.DataTable(<?=$json1?>);
var data2 = new google.visualization.DataTable(<?=$json2?>);
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart1 = new google.visualization.AnnotationChart(document.getElementById('chart1'));
var options = {
displayAnnotations: false,
thickness: 2,
colors: ['red', 'blue'],
interpolateNulls: true,
curveType: 'function',
};
chart1.draw(joinedData, options);
}
produces:
http://imgur.com/r5sqtvd
Whereas:
<script type='text/javascript'>
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = new google.visualization.DataTable(<?=$json1?>);
var data2 = new google.visualization.DataTable(<?=$json2?>);
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart1 = new google.visualization.LineChart(document.getElementById('chart1'));
var options = {
displayAnnotations: false,
thickness: 2,
colors: ['red', 'blue'],
interpolateNulls: true,
curveType: 'function',
};
chart1.draw(joinedData, options);
}
produces:
http://imgur.com/qk79hob
What am I missing?
Thanks in Advance!
AnnotationChart has no option interpolateNulls. See google docs Annotation Chart.

Binding Events in google pie chart

I have a Pie Charts generated by Google Chart API. The code for the chart goes as Below
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart1);
function drawChart1()
{
var data = google.visualization.arrayToDataTable([
['Location', 'Value'],
["Location A", 20 ],
["Location B", 32],
["Location C", 12],
["Location D", 20],
["Location E", 2],
["Location F", 20],
["Location H", 10]
]);
var options = {
colors : ['#00918c', '#d0c500','#945a94', '#84ac43', '#ea8c1c', '#006daf', '#c54d4d'],
is3D : 'false',
isHTML : 'false',
height : 200,
width : 285,
backgroundColor : "transparent",
chartArea : {left:0,top:0,width:"100%",height:"100%"},
legend : {position: 'right', alignment: "end"}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
The Link for the chart is as Below
Click to see Chart
I want to capture the event in the chart when they click any pie area.
Suppose if they click on Location A pie in pie chart I want a function that displays alert message as Location A Clicked and same for other pie's in chart.
Thanks for reply
I added the code below and its working fine now.
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
function selectHandler()
{
var selectedItem = chart.getSelection()[0];
if (selectedItem)
{
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
See the link for Binding Events in google pie chart.
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
} </script>