Retrieve value column header google visualisation - javascript

I want to retrieve the value of the column header when a user clicks on 1 of the bars of the chart. A report should be generated with the parameters I retrieve from the chart. This is what I have so far:
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.arrayToDataTable([
['Month', '2014', '2015'],
['Jan', 0, 200.00],
['Feb', 0, 400.00],
['Mar', 0, 700.00],
['Apr', 0, 100.00],
['May', 400.00, 900.00],
['Jun', 1100.00, 0],
['Jul', 3400.00, 0],
['Aug', 2500.00, 0],
['Sep', 2450.00, 0],
['Oct', 3170.00, 0],
['Nov', 2500.00, 0],
['Dec', 1979.00, 0]
]);
var options = {
title: 'Raised'
};
var chart = new google.charts.Bar(document.getElementById('chart_div_month'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var month = data.getValue(selectedItem.row, 0);
var year = data.getValue(0, selectedItem.column);
window.location = 'report.php?submit=Submit&year=' + year + '&month=' + month;
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
I am able to retrieve the month parameter, but not the year.

Reading about google chart tables at their API page it says that
getSelection() - Standard getSelection implementation.
Selection elements are all row elements.
Can return more than one selected row.
So getSelection() doesn't select any column, and therefore var year = data.getValue(0, selectedItem.column);won't work.
Why it is like this I don't know, as the getSelection() returns both a row and a column, but the column is always null (thought it hasn't always been like this, there are loads of examples where people show how it works, but they are all broken today).
I have seen an approach that uses standard javascript (or was it jQuery?) to detect which column is clicked (clicked, not selected) by listening for mouseclicks on tds and getting the column property that way, but I can't seem to find it.

Related

Add Region URL to Geochart

I am creating a map using Google Geochart and need a listener so that when the user clicks on a region it loads a given URL.
My code is:
google.load('visualization', '1.1', {packages: ['geochart'], callback: drawVisualization});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country', 'Value', {role: 'tooltip', p:{html:true}}],
['US', 20, 'Test'],
['Canada', 20, 'http://www.ipfa.org/council/branches/106/ipfa-canada/'],
['GB', 20, 'http://www.ipfa.org/council/branches/52/ipfa-uk/'],
]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
var row = selection[0].row;
var url = data.getValue(row, 3);
window.open(url);
});
chart.draw(data, {
width: 800,
height: 600,
tooltip: {
isHtml: true
}
}
);
}
The URL listener works on another map I use, what am I doing wrong to not work on this one?
There are two issues. First, you are using the wrong index to reference your URLs; they are in column 2, not column 3 (which doesn't exist):
var url = data.getValue(row, 3);
Second, one of your URL's (for the US) is an anchor tag, which won't work if passed to the window.open call. If you want anchor tags in the tooltips, set the value of the cell to the URL and formatted value of the URL column to the anchor tag:
['US', 20, {v: 'http://www.ipfa.org/council/branches/39/ipfa-americas/', f: 'Test'}]
I would also suggest testing for the length of the selection array, because it is possible for the selection array to be empty if the user clicks a region twice in a row (the second click deselects the region), which would cause this line to throw an error:
var row = selection[0].row;
I suggest using this instead:
var selection = chart.getSelection();
if (selection.length) {
var url = data.getValue(selection[0].row, 2);
window.open(url);
}

Show percentage in jqplot piechart tooltip

I'm using primefaces with jqplot library.
In my piechart i have the extender property and in the javascript function i have this:
this.cfg.highlighter = {
show:true,
tooltipLocation: 'n',
tooltipAxes: 'y',
useAxesFormatters: false,
tooltipFormatString: '%s'
}
The tooltip shows section value, but not section percentage.
Anybody knows how to show percentage value in tooltip?
Thanks.
You can bind the highlight event in order to modify the tooltip :
$("#chart1").bind('jqplotDataHighlight', function(ev, seriesIndex, pointIndex, data) {
var highlightToolTip = $(".jqplot-highlighter-tooltip");
var pct = Math.round(data[1]/total*100);
highlightToolTip.html(data[0]+", "+pct+"%");
});
Where :
data1 is the value of the highlighted slice,
data[0] is the label of the highlighted slice,
total is a variable containing the total value of your plot built here :
data = [
['Heavy Industry', 12],['Retail', 9], ['Light Industry', 14],
['Out of home', 16],['Commuting', 7], ['Orientation', 9]
];
var total = 0;
$(data).map(function(){total += this[1];})
Please see a working example on
fiddle here

Enabling/disabling legend and its corresponding row onclick in Google charts

My requirement is,
After a google chart gets loaded, if I click the legend, the legend should be grayed out and its corresponding value in the graph should be removed.
When I click the grayed out legend, the legend should be highlighted as it was before and the removed value should once again be added to the graph.
I am able to do the 50 % of the first part with the below code:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// 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.
var duplicateChartData = new Array();
var unSelectedArray = new Array();
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
duplicateChartData = new Array();
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'));
duplicateChartData = data;
function selectHandler() {
var selectedItem = chart.getSelection()[0];
var selectedRow = selectedItem.row;
var isUnSelected = unSelectedArray[selectedRow]
if (selectedItem && !isUnSelected) {
data.setValue(selectedRow, 1, 0);
chart.draw(data, options);
unSelectedArray[selectedRow] = true;
}
if(isUnSelected){
data.setValue(selectedRow, 1, duplicateChartData.getValue(selectedRow,1));
unSelectedArray[selectedRow] = false;
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
I basically setValue as 0 for the selected value and try to reset when clicked again. But whenever a zero is set the legend and data gets deleted. But what I want is thw legend to just gray out. ow to achieve this. Please help me.
I did this for line chart. It satisfies your both requirements. Hope this will help you.
google.visualization.events.addListener(chart, 'select', function () {
var sel = chart.getSelection();
// if selection length is 0, we deselected an element
if (sel.length > 0) {
// if row is undefined, we clicked on the legend
if (typeof sel[0].row === 'undefined') {
var col = sel[0].column;
if (columns[col] == col) {
// hide the data series
columns[col] = {
label: data.getColumnLabel(col),
type: data.getColumnType(col),
calc: function () {
return null;
}
};
// grey out the legend entry
series[col - 1].color = '#CCCCCC';
}
else {
// show the data series
columns[col] = col;
series[col - 1].color = null;
}
var view = new google.visualization.DataView(data);
view.setColumns(columns);
chart.draw(view, options);
}
}
});
Here is the working sample jqfaq.com
Awesome piece of code Abinaya (sorry i cld not +1 im still a newbie here at SO), just what i was looking for, thanks, just a minor correction, based on the comment at jqfaq.com. tried it out and it works 100%.
// if row is undefined, we clicked on the legend
//if (typeof sel[0].row === 'undefined') { *** doesn't seem to work
if (sel[0].row === null) { // this works
checkout the amended jsfiddle
I also had been searching for code on how to get the selected legend label and your code also does that using this line of code
//get selected legend label
data.getColumnLabel(col)
thanks again

get data from selected slice of google charts PieChart

i have big trouble trying to get the value of the selected slice of a PieChart when its clicked.
The documentation says:
selection_array: An array of selected objects, each one describing a
data element in the underlying table used to create the visualization
(a DataView or a DataTable). Each object has properties row and/or
column, with the index of the row and/or column of the selected item
in the underlying DataTable. If the row property is null, then the
selection is a column; if the column property is null, then the
selection is a row; if both are non-null, then it is a specific data
*item. You can call the DataTable.getValue()* method to get the value of
the selected item. The retrieved array can be passed into
setSelection()
in my case i get null from getSelection(), then i couldnt figure out what to do to get the value i want (the label of the column corresponding to that slice).
Any answer will be very apreciated :)
the example code of what im doing:
google.load('visualization', '1', {packages: ['controls']});
google.setOnLoadCallback(drawVisualization);
var data;
var pie_area;
function drawVisualization() {
// Prepare the data
data = google.visualization.arrayToDataTable([
["rbd", "nombre", "area", "dependencia", "simceMat", "ubicacionLon", "ubicacionLat", "simceLen", "nivel"],
[22616, "Colegio Mozart", "Urbana", "Part_Sub", 228, -72.981148, -41.479872, 254, "Basico"],
[22686,"Escuela Basica Camelias","Urbana","Muni",228,-72.980075,-41.474599,253, "Medio"],
[40351,"Colegio Bosquemar","Urbana","Part_Sub",290,-72.981148,-41.479872,280, "Medio"],
[7633,"Escuela Capitan Arturo Prat Chacon","Urbana","Muni",317,-72.909565,-41.474567,314, "Basico"],
[7659,"Escuela Rural Alerce","Rural","Muni",230,-72.91767,-41.399121,249, "Basico"],
[7671,"Escuela Rural Lagunitas","Rural","Muni",261,-72.964282,-41.459485,269, "Medio"],
[7690,"Escuela Rural Rio Blanco","Rural","Muni",217,-72.638597,-41.455786,229, "Medio"],
[7700,"Colegio San Francisco Javier","Urbana","Part",305,-72.942089,-41.470351,303, "Basico"],
[7717,"Instituto Aleman de Puerto Montt","Urbana","Part",321,-72.932482,-41.470001,310, "Medio"],
[7718,"The American School","Urbana","Part",317,-72.909,-41.456,314, "Medio"]
]);
var fltArea = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'f1',
'options': {
'filterColumnLabel': 'area',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
pie_area = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart2',
'options': {
'width': 300,
'height': 300,
'legend': 'none',
'title': 'Area',
'pieSliceText': 'label'
},
'view': {'columns': [2]}
});
new google.visualization.Dashboard(document.getElementById('dashboard')).bind([fltArea], [pie_area]).draw(data);
google.visualization.events.addListener(pie_area, 'select', onAreaSliceSelected);
}
function onAreaSliceSelected(){
var sel = pie_area.getChart().getSelection(); //is always null
console.log('you selected '+sel); //displays you selected null
}
The issue is in how your chart/data is set up.
You are currently aggregating all the data from column 2 to generate the chart. In this case you have 7 Urbana, and 3 Rural for your values, so it aggregates those 10 rows into two categories. Since each slice of the pie refers to a set of aggregate values, and pie charts only allow a single value to be selected, you can't get the selection of three rows that way.
Additionally, your category selector doesn't provide much use as it currently is, because if you select either Urbana or Rural, you end up getting a pie chart showing 100% of a single category.
If you set up your data differently, you will properly get an array of objects whenever you select a slice, as in this example:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
// Create and draw the visualization.
pieChart = new google.visualization.PieChart(document.getElementById('visualization'));
pieChart.draw(data, {title:"So, how was your day?"});
google.visualization.events.addListener(pieChart, 'select', onAreaSliceSelected);
}
function onAreaSliceSelected(){
var sel = pieChart.getSelection(); //is always null
alert('you selected '+sel); //displays you selected null
}

Google charts display Money not Percentages

Given the data for a pie chart:
data = new google.visualization.arrayToDataTable([
['Sales', 'Revenue Distribution'],
['Author', 5],
['Company', 2],
['Tax', 0.4],
['Payment Processors', 0.9]
]);
drawChart();
How can I make it display as dollar amounts? Either in the tooltip or on the actual graph itself (both would be preferable!)
For example, ideally this would work:
data = new google.visualization.arrayToDataTable([
['Sales', 'Revenue Distribution'],
['Author', '$5'],
['Company', '$2'],
['Tax', '$0.4'],
['Payment Processors', '$0.9']
]);
drawChart();
It is possible and it will apply it to both the slice and the tooltip. What you need to include is a number formatter.
The key things are to apply the following before you 'create' the chart.
var formatter = new google.visualization.NumberFormat({
prefix: '$'
});
formatter.format(data, 1);
var options = {
pieSliceText: 'value'
};
This first creates the formatter and applies it to the data, the next option then forces the pie chart to show the formatted value, rather than the calculated percentage. You can see it working in this jsfiddle.
Inspired and adapted by the answer here: Formatting google charts programmatically

Categories

Resources