Google Bar Chart custom tooltip does not work - google-visualization

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>

Related

Google charts error:every row given must be either null or an array

I am working on a website that is intended to show some basic Google charts. The data comes from a text file that i retrieve through Ajax. It's got a x, y value and an annotation field. The data looks like this:
[[-0.8, -0.47, "100-005-10"],
[-0.7, -0.46, "100-005-9"],
[-0.6, -0.45, "100-005-8"],
[-0.5, -0.44, "100-005-7"]]
Here's my code:
<script >
var xmlhttp = new XMLHttpRequest();
var array;
xmlhttp.onreadystatechange = function() {
array = this.responseText;
};
xmlhttp.open("GET", "array.array", true);
xmlhttp.send();
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($.parseJSON(array), true)
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn({type: 'string', role: 'annotation'});
data.addRow(array);
var options = {
legend: 'none',
colors: ['#087037'],
selectionMode: 'single',
tooltip: {trigger: 'selection'},
pointSize: 12,
animation: {
duration: 200,
easing: 'inAndOut',
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('animatedshapes_div'));
chart.draw(data, options);
}
</script>
When i run the code, i get this error message:
Error: If argument is given to addRow, it must be an array, or null
I just don't know how to transform the plain text from the ajax response to an array.
try using JSON.parse to convert the string to an actual array...
data.addRows(JSON.parse(array));
In one of the case, need to add Square brackets []
self.tableValues.forEach((row: any) => {
if(row) {
dataTable.addRows([row]); // <-- row is array; so try [row]
}
});

Google Visualization ColorFormat Exact Match String

Is it possible to colour a text column based off an exact match? I have tried setting the from and to, to the same value but it doesn't colour the cell?
formatter.addRange('danger', 'danger', 'red', 'white');
Thanks
The high boundary, or To value, is non-inclusive
so it has to be something after 'danger'
including a space at the end will color the cell
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'string');
data.addColumn('number', 'number');
data.addRow(['danger', 0]);
data.addRow(['safe', 1000]);
data.addRow(['unknown', 1001]);
var formatColor = new google.visualization.ColorFormat();
formatColor.addRange('danger', 'danger ', 'white', 'red');
formatColor.addRange(1000, 1001, 'white', 'green');
formatColor.format(data, 0);
formatColor.format(data, 1);
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(data, {
allowHtml: true
});
},
packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google column charts X-axis label different from value

I'd like to create column chart with X axis numeric values 1, 2, 3, 4 ... N and Y value of course different on every column.
I can't find out how to change labels on X line under bars, to string. For example - 1 could be marked as Elephant, 2 as Horse etc.
I could use string as X values, but then there is no way to get zoom working. At least, I didn't find any way to get it working.
simple example with strings, I'd like to achieve same appearance as this one, but with numeric values on X axis.
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'animal');
data.addColumn('number', 'count');
data.addRows([
['Elephant', 5],
['Horse', 2],
['Dog', 7],
['Cat', 4],
]);
var options = {
explorer: {
axis: 'horizontal',
keepInBounds: true,
},
title: 'Testing',
hAxis: {
title: 'Animal',
},
vAxis: {
title: 'number'
}
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
Chart should look like this, but with working zoom:
Chart example
to use string labels on a continuous axis,
you will need to provide your own ticks
using object notation, provide the value (v:) and formatted value (f:)
{v: 1, f: 'Elephant'}
see following working snippet...
google.charts.load('current', {
callback: drawBasic,
packages: ['corechart']
});
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'animal');
data.addColumn('number', 'count');
data.addRows([
[1, 5],
[2, 2],
[3, 7],
[4, 4]
]);
var options = {
explorer: {
axis: 'horizontal'
},
title: 'Testing',
hAxis: {
ticks: [
{v: 1, f: 'Elephant'},
{v: 2, f: 'Horse'},
{v: 3, f: 'Dog'},
{v: 4, f: 'Cat'}
],
title: 'Animal',
},
vAxis: {
title: 'number'
}
};
var chart = new google.visualization.ColumnChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Column Chart: All series on a given axis must be of the same data type

What am i doing wrong with the following code to get an error All series on a given axis must be of the same data type
function drawVisualization(){
var performanceJson = $.ajax({
url : "{% url json_data %}",
type:"GET",
dataType: "json",
cache: false,
async: false}).responseJSON;
var performanceData = new google.visualization.DataTable();
performanceData.addColumn('string', 'Question');
performanceData.addColumn('string', 'Headings');
performanceData.addColumn('number', 'TotalScore');
performanceData.addColumn('number', 'Score');
performanceData.addRows(performanceJson);
var performanceOptions = {
title : 'Performance Report',
subtitle: 'Based on a scale of 1 to 7',
hAxis : {title:'Question', titleTextStyle:{color:'red'}},
vAxis : {title:'Scores'},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(performanceData, performanceOptions);
}
The performanceJson variable has the value:
[["No. of people", "Area", 6, 1], ["Scholars", "Standard", 12, 2], ["Co-ordination", "Standard", 18, 14]]
For a ColumnChart all columns(except the first) have to be of type number.
Column #2 is of type string, column#3 and column #4 are of type number, so the error-message should be clear.
I'm not sure for what column #2 is good for, but you may not use this column as data-column
You may e.g. use this column as annotation:
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization(){
var performanceJson = [["No. of people", "Area", 6, 1],
["Scholars", "Standard", 12, 2],
["Co-ordination", "Standard", 18, 14]];
var performanceData = new google.visualization.DataTable();
performanceData.addColumn('string', 'Question');
performanceData.addColumn({type:'string',role:'annotation'});
performanceData.addColumn('number', 'TotalScore');
performanceData.addColumn('number', 'Score');
performanceData.addRows(performanceJson);
var performanceOptions = {
title : 'Performance Report',
subtitle: 'Based on a scale of 1 to 7',
hAxis : {title:'Question', titleTextStyle:{color:'red'}},
vAxis : {title:'Scores'},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(performanceData, performanceOptions);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>

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>