get data from selected slice of google charts PieChart - javascript

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
}

Related

Retrieve value column header google visualisation

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.

Google Charts table sorting via keyboard

I'm trying to use the Google Charts API on a website that must be 100% Section 508 compliant, i.e., accessible to those with disabilities.
Google Charts tables have a 'sort' function but in its default state column headers cannot be selected by the keyboard for sorting.
I can use some Javascript to inject "tabindex=0" attributes into the column header elements easily enough, and as expected, that makes the column headers focusable...but surprisingly, clicking on the enter key does nothing. Same thing happens if I make the sort arrows inside the column headers focusable - I can focus on it using TAB, but I still can't select it.
Does anyone have a solution for this? If there is no straightforward way to create a table that's sortable using only the keyboard, is there a workaround to transform a focus/keypress into an onclick?
I created a fiddle that uses jQuery to redraw the chart on a keypress:
http://jsfiddle.net/mVYeL/
Here's the relevant code:
google.load('visualization', '1.1', {
'packages': ['table']
});
google.setOnLoadCallback(drawStuff);
var table;
var data;
var options = {sortAscending:true};
function sortTable(col) {
if (options.sortColumn == col) {
options.sortAscending = !options.sortAscending;
} else {
options.sortAscending = true;
}
options.sortColumn = col;
table.draw(data, options);
}
$(document).keydown(function(e){
if (e.keyCode==49) { sortTable(0); }
if (e.keyCode==50) { sortTable(1); }
if (e.keyCode==51) { sortTable(2); }
});
function drawStuff() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, true],
['Jim', {v:8000, f: '$8,000'}, false],
['Alice', {v: 12500, f: '$12,500'}, true],
['Bob', {v: 7000, f: '$7,000'}, true]
]);
// Instantiate and draw our chart, passing in some options.
table = new google.visualization.Table(document.getElementById('chart_div'));
table.draw(data, options);
};

How to add more href elements for each column in the chart with Javascript

What I am doing here is add a link for each column but it works only with the first link1's column.
Please help me to correct this problem and make my code shorter when there are not only 3 links for each Plant.
['Year', 'link1', 'Dollars', 'link2', 'Conts', 'link3', 'Quantity'],
['Plant 1', 'http://google.com', 1000, 'http://bing.com', 400, 'http://alexa/com', 2000],
['Tan Thanh', 'http://dell.com', 1170, 'http://lenovo.com', 460, 'http://hp.com', 1420],
['Plant 3', 'http://w3schools.com', 660, 'http://microsoft.com', 1120, 'http://adobe.com', 1080],
['Plant 4', 'http://apple.com', 1030, 'http://htc.com', 540, 'http://samsung.com', 2240]
Summary:
In Plant 1:
Problem goes here:
Click on the first column (blue column), a new tab appears with
http://google.com.
Click on the second column (red column), a new tab appears with
http://google.com.
Click on the third column (yellow column), a new tab appears with
http://google.com.
It must be:
Click on the first column (blue column), a new tab appears with
http://google.com.
Click on the second column (red column), a new tab appears with
http://bing.com.
Click on the third column (yellow column), a new tab appears with
http://alexa/com.
Demo
HTML:
<div id="chart_div" style="width: 550px; height: 500px;"></div>
Javascript:
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'link1', 'Dollars', 'link2', 'Conts', 'link3', 'Quantity'],
['Plant 1', 'http://google.com', 1000, 'http://bing.com', 400, 'http://alexa/com', 2000],
['Tan Thanh', 'http://dell.com', 1170, 'http://lenovo.com', 460, 'http://hp.com', 1420],
['Plant 3', 'http://w3schools.com', 660, 'http://microsoft.com', 1120, 'http://adobe.com', 1080],
['Plant 4', 'http://apple.com', 1030, 'http://htc.com', 540, 'http://samsung.com', 2240]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 2, 4, 6]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
function selectHandler1() {
window.open(data.getValue(chart.getSelection()[0]['row'], 1), '_blank');
}
function selectHandler2() {
window.open(data.getValue(chart.getSelection()[0]['row'], 3), '_blank');
}
function selectHandler3() {
window.open(data.getValue(chart.getSelection()[0]['row'], 5), '_blank');
}
// Add our selection handler.
google.visualization.events.addListener(chart, 'select', selectHandler1);
google.visualization.events.addListener(chart, 'select', selectHandler2);
google.visualization.events.addListener(chart, 'select', selectHandler3);
}
Use a single event handler, and fetch the relevant URL based on the column index of the selected element:
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
// test selection array length, since it can be 0 if the user deselects an element
if (selection.length) {
var row = selection[0].row;
// convert the view column index to the table column index,
// then subtract 1 to get the URL index
var urlCol = view.getTableColumnIndex(selection[0].column) - 1;
window.open(data.getValue(row, urlCol), '_blank');
}
});

Organizing graph options in Google Charts

I'm creating a handful of pie charts using Google Charts. The majority of the graph options for the charts I'm creating are the same, except the titles. Is it possible to maintain a default set of options but write certain specific options for each graph (in this case, I just need to set a title).
Here's an example of the code I'm using:
var graphOptions = {
is3D: true,
pieSliceText: 'label',
colors: ['#F9B641', '#FBCB75', '#FCE1B0', '#FFF8EB', '#FFFFFF'],
backgroundColor: 'transparent',
titleTextStyle: {
color: '#FFF'
},
legend: {
textStyle: {
color: '#FFF'
}
},
chartArea: {
width: '90%',
height: '80%'
}
};
function pieChart1() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 216],
['Female', 238]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart1'));
chart.draw(data, graphOptions);
}
function pieChart2() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 116],
['Female', 98]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart2'));
chart.draw(data, graphOptions);
}
How would I go about setting the title option for each graph while still pulling the options from graphOptions?
As David explained, you can create an options object, and then edit properties of that object individually.
Here is a jsfiddle that shows it in action.
Note: you cannot see the titles because the BG and font color is white. Just do a ctrl+a to select everything and see them hidden there
Basically, you create a variable both functions can access (in your case graphOptions). In each function you set a new variable called options to equal graphOptions. You can then change the title property of the options variable to whatever you want without changing your default options template graphOptions, and use the options variable to draw the graph.
For your code, that means adding this code to each function:
var options = graphOptions;
options.title = "Pie Chart X"
You can change the title to whatever is appropriate, different for each graph. Then in the graph draw command, you change graphOptions to options to get
chart.draw(data, options);
Normally you'd do:
var options = { title: 'My Chat Title' };
In your case add title to your graphOptions object then do:
graphOptions.title = "The New Title";
for each graph.

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