Add additional data to google chart dataTable - google-visualization

I'm using google scatterchart to show where defects are on a surface. All defects have an ID, when I click on a point I want an event to fire from where I can get that ID and do other stuff with it.
In google chart one can wire an selecthandler from where I can get what's selected, but how do I add an ID (or any other data) in the dataTable to a point without it being displayed?
For example:
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('number', 'Width');
dataTable.addColumn('number', 'Yellow');
dataTable.addColumn({ type: 'string', role: 'tooltip', 'p': { 'html': true } });
dataTable.addColumn('number', 'Red');
dataTable.addColumn({ type: 'string', role: 'tooltip', 'p': { 'html': true } });
dataTable.addColumn('number', 'Id'); <-- this doesn't work
The last column I want to add the ID of the defect and retrieve it via the selectHandler.
dataTable.addRow([123, 123, 'some tooltip', null, null, 999]);
Here I added ID 999 to the table. But I don't want the chart to display it. How do I add additional (hidden) data to a point?

You can add extra columns containing any information you want, and then hide them with a DataView:
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('number', 'Width');
dataTable.addColumn('number', 'Yellow');
dataTable.addColumn({ type: 'string', role: 'tooltip', 'p': { 'html': true } });
dataTable.addColumn('number', 'Red');
dataTable.addColumn({ type: 'string', role: 'tooltip', 'p': { 'html': true } });
dataTable.addColumn('number', 'Id');
// populate dataTable
var view = new google.visualization.DataView(dataTable);
// exclude column 5 (Id)
view.setColumns([0, 1, 2, 3, 4]);
Then draw your chart using the DataView instead of the DataTable.

setRowProperties(rowIndex, properties) would work in this case, remove Id column and add dataTable.setRowProperties(0,{'id':'999'});
You can get the property of the row by using getRowProperties(rowIndex);

Related

How to get data point x/y values when Google Visualisation line chart data point clicked [duplicate]

i want to take out 'text value' on mouse click on anywhere on the row/svg image ,for i.e. in the below image if i click anywhere on 2nd blue highlighted row, then i should be able to get the text 'Adams' as alert. I tried to iterate thru svg elements but svg elements are created horizontally rather then vertically
you can use the 'select' event, to determine the value selected
when the 'select' event fires, check chart.getSelection()
google.visualization.events.addListener(chart, 'select', function () {
selection = chart.getSelection();
if (selection.length > 0) {
console.log(dataTable.getValue(selection[0].row, 0));
}
});
getSelection returns an array of the selected rows,
Timeline charts only allow one row to be selected at a time,
so the selection will always be in the first element
chart.getSelection()[0]
each element in the array will have properties for row and column
(column will always be null for a Timeline chart)
once you have the row, you can use getValue on the DataTable
dataTable.getValue(selection[0].row, 0)
getValue takes two arguments, rowIndex and columnIndex
use 0 to get the value of the first column
see following working snippet...
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'President' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
[ 'Adams', new Date(1797, 2, 4), new Date(1801, 2, 4) ],
[ 'Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4) ]]);
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
google.visualization.events.addListener(chart, 'select', function () {
selection = chart.getSelection();
if (selection.length > 0) {
console.log(dataTable.getValue(selection[0].row, 0));
}
});
chart.draw(dataTable);
},
packages: ['timeline']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>
EDIT
to capture the click anywhere on the row, outside the colored bar,
use the 'ready' event to find the svg elements and add a listener
the elements will have an x attribute of zero (0)
and a fill attribute other than 'none'
since the number of elements will match the number of rows,
we can use the index of the element, amongst its peers, to find the value
see following working snippet,
both the 'select' and 'click' events are used to find the value clicked
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'President' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
[ 'Adams', new Date(1797, 2, 4), new Date(1801, 2, 4) ],
[ 'Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4) ]]);
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var saveRows = [];
google.visualization.events.addListener(chart, 'ready', function () {
chartRows = container.getElementsByTagName('rect');
Array.prototype.forEach.call(chartRows, function(row) {
if ((parseInt(row.getAttribute('x')) === 0) && (row.getAttribute('fill') !== 'none')) {
saveRows.push(row);
row.addEventListener('click', function (e) {
for (var i = 0; i < saveRows.length; i++) {
if (e.target === saveRows[i]) {
getRowLabel(i);
break;
}
}
}, false);
}
});
});
google.visualization.events.addListener(chart, 'select', function () {
selection = chart.getSelection();
if (selection.length > 0) {
getRowLabel(selection[0].row);
}
});
function getRowLabel(index) {
console.log(dataTable.getValue(index, 0));
}
chart.draw(dataTable);
},
packages: ['timeline']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>

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>

Column data label on google bar chart

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);
}

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}

How to select a card in a carousel by menu item in a docked menu list in Sencha touch?

I cannot figure out how I can retrieve a given Data item in a store (id-number) to send it to the "setActiveItem" method in a listener:
So I have a store - model:
Ext.regModel('PictureItem', {
fields: ['id', 'titel', 'url']
});
var pictureItems = new Ext.data.Store({
model: 'PictureItem',
data: [
{id:1, titel:'page 1', url:'http://placekitten.com/1024/768'},
{id:2, titel:'page 2', url:'http://placekitten.com/1024/768'},
{id:3, titel:'page 3', url:'http://placekitten.com/1024/768'},
]
});
Here is my menuList called "leftList":
var leftList = new Ext.List({
dock: 'left',
id:'list1',
width: 135,
overlay: true,
itemTpl: '{titel}',
singleSelect: true,
defaults: {
cls: 'pic'
},
store: pictureItems,
listeners:{
selectionchange: function (model, records) {
if (records[0]) {
Ext.getCmp('karte').setActiveItem(!!!Here the number of the selected Item
or respondend "id" in the data store!!!);
}
}
}
});
and the carousel....
var carousel = new Ext.Carousel({
id: 'karte',
defaults: {
cls: 'card'
},
items: [{
scroll: 'vertical',
title: 'Tab 1',
html: '<img class="orientation" alt="" src="img_winkel/titel_v.jpg">'
},
If I call
Ext.getCmp('karte').setActiveItem(2);
it works with the called card - but how can I get the number from the id of the selected item in the menu List /store????
By the way: what does mean:
if (records[0]) {
why [0]?
I FOUND THE ANSWER FOR MYSELF - IT'S EASY:
Ext.getCmp('karte').setActiveItem(records[0].get('id'), {type: 'slide', direction: 'left'});
The secret to get the record-entry is ".get()":
records[0].get('arrayfield')
So now I can change the activeItem in the carousel easely...