Google Timeline Chart with more than one column role - charts

I am trying to draw a timeline chart and add two column roles, one for an HTML link (tooltip column role) and another for styling (style).
I can use either one of them successfully but not both at the same time.
For example, here's a sample of my code:
var container = document.getElementById('mychart');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Position' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'string', role: 'style' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addColumn({ type: 'string', role: 'tooltip', id: 'link', 'p': {'html': true} });
I believe it has to do with the placement of the columns. In the example above, styling is done correctly but the hyperlink is being formed with the tooltip content instead of the actual column role data I'm passing.
If I remove the style column role the hyperlink works fine, even when placed last in the columns. It's leading me to think that I can't have more than one column role but that's not what the documentation says.
Any clues would be appreciated.

In order to have a column have a clickable hyperlink you an extra piece of code:
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
if (selection.length > 0) {
window.open(dataTable.getValue(selection[0].row, 3), '_blank');
}
});
My single row of data for debugging purposes was:
dataTable.addRows([
['My text here', 'bar label', '#676767', 'https://www.google.com', new Date(2019, 12, 22), new Date(2019, 12, 26)]]);
I had shuffled the columns around and was pointing to the wrong column. Just had to change to the right column above to get it to work (column 3, being zero-based).

Related

Google Visualization Charts Timeline - tooltip dateformat not working

I'm trying to change the Dateformat in a Google Charts Timeline tooltip. For some reason it's not working at all. I've tried this pattern 'dd.MM, yyyy' to change the hAxis via the options which worked just fine, but the tooltip doesn't change.
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'string', id: 'City' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
// some php code to echo Rows that look like this
['Mike', 'London', new Date(2021,4,25), new Date(2021,5,18)],
['Peter', 'Berlin', new Date(2021,3,10), new Date(2021,6,20)]
]);
var formatter = new google.visualization.DateFormat({ pattern: 'dd.MM, yyyy' });
formatter.format(dataTable, 2);
formatter.format(dataTable, 3);
var chart = new google.visualization.Timeline(document.getElementById('timeline'));
chart.draw(dataTable);
}
Timeline still shows this

How to find google charts (Sankey) select events selection data - including tooltip column

I am creating a Sankey chart via react-google-charts. Each time when clicked on the link between the nodes I am printing the data which has been working fine until recently.
Assume my Sankey diagram to be like this and I clicked on the link between A & P:
[A] ----> [P] ------> [X]
[B] ----> [Q] ------> [Y]
[C] ----> [R] ------> [Z]
let myOptions = {
sankey: {
link: {
interactivity: true
}
}
}
...
...
<Chart
chartType='Sankey'
data={
[
['From', 'To', 'Weight', {role: 'tooltip', type: 'string'}],
['A', 'P', 1, 'i111'],
['B', 'Q', 1, 'j333'],
['C', 'R', 1, 'k444'],
['P', 'X', 1, 'l555'],
['Q', 'Y', 1, 'l666'],
['R', 'Z', 1, 'n999']
]
}
columns
options={myOptions}
chartEvents={[
{
eventName: 'select',
callback: ({chartWrapper}) => {
const chart = chartWrapper.getChart()
const selection = chart.getSelection()
if (selection.length === 1) {
const [selectedItem] = selection
const {row} = selectedItem
// below line was working until recently, but not anymore
console.log(chartWrapper.getDataTable().Vf[row].c)
// updated the property key after which it works
console.log(chartWrapper.getDataTable().Wf[row].c)
// returns [{v: 'A'}, {v: 'P'}, {v: 1}, {v: 'i111'}]
}
}
}
]}
/>
I can also get the selection data like this but it does not give me the final column value i.e., tooltip in this case.
console.log(chartWrapper.getDataTable().cache[row])
// returns [{Me: 'A'}, {Me: 'P'}, {Me: '1'}]
Is there any other way for me to get the data apart from what I have done above? Especially the line
chartWrapper.getDataTable().Wf[row].c
Having a property value hardcoded has broken my UI thrice in recent times and I would like to avoid doing so.
to my knowledge, the sankey chart will only allow you to select the nodes,
not the links between the nodes.
and this is only allowed after setting the interactivity option.
options: {
sankey: {
node: {
interactivity: true
}
}
}
the selection returns the name of the node selected,
which can appear in the data table multiple times.
in the following example, I've added an additional "P" node to demonstrate.
when the select event fires, you can get the name of the node selected from the chart's selection.
then you must search through the rows in the data table to find the row with the matching node name.
once you've found the data table row for the selected node name,
you can use data table method getValue to retrieve the values for that row.
see following working snippet...
google.charts.load('current', {
packages: ['controls', 'sankey']
}).then(function () {
var chartWrapper = new google.visualization.ChartWrapper({
chartType: 'Sankey',
containerId: 'chart',
dataTable: google.visualization.arrayToDataTable([
['From', 'To', 'Weight', {role: 'tooltip', type: 'string'}],
['A', 'P', 1, 'i111'],
['B', 'Q', 1, 'j333'],
['C', 'R', 1, 'k444'],
['P', 'X', 1, 'l555'],
['P', 'Y', 2, 'l555'],
['Q', 'Y', 1, 'l666'],
['R', 'Z', 1, 'n999']
]),
options: {
sankey: {
node: {
interactivity: true
}
}
}
});
google.visualization.events.addListener(chartWrapper, 'ready', function () {
google.visualization.events.addListener(chartWrapper.getChart(), 'select', selectEvent);
});
chartWrapper.draw();
function selectEvent() {
var chart = chartWrapper.getChart();
var data = chartWrapper.getDataTable();
var selection = chart.getSelection();
if (selection.length > 0) {
// find data table rows for selected node name
var nodeName = selection[0].name;
var nodeRows = data.getFilteredRows([{
column: 0,
value: nodeName
}]);
// find row values for selected node name
nodeRows.forEach(function (row) {
var valFrom = data.getValue(row, 0);
var valTo = data.getValue(row, 1);
var valWeight = data.getValue(row, 2);
var valTooltip = data.getValue(row, 3);
console.log(valFrom, valTo, valWeight, valTooltip);
});
}
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Tooltip doesn't work in Google Scatter Chart

I'm trying to create a scatter plot using Google charts and I don't seem to be able to add a column to be a tooltip. I read various sources that state that the data definition should be as:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
// A column for custom tooltip content
data.addColumn({type: 'string',role: 'tooltip',});
data.addRows([
['Name1', 1000, 'Tooltip string'],
['Name2', 1170, 'Tooltip string'],
['Name3', 660, 'Tooltip string'],
]);
However, it doesn't work.
JSFiddle to demonstrate the issue: https://jsfiddle.net/shakedk/c37L0d1n/
column roles are not supported by material charts,
along with several other options.
see --> Tracking Issue for Material Chart Feature Parity
for custom tooltips, you will need to use a classic chart.
material = google.charts.Scatter -- package: 'scatter'
classic = google.visualization.ScatterChart -- package: 'corechart'
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
// A column for custom tooltip content
data.addColumn({
type: 'string',
role: 'tooltip',
});
data.addRows([
['Name1', 1000, 'Tooltip string'],
['Name2', 1170, 'Tooltip string'],
['Name3', 660, 'Tooltip string'],
]);
var options = {
width: 800,
height: 500,
chart: {
title: 'Example',
},
};
var chart = new google.visualization.ScatterChart(document.getElementById('scatterchart_material'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="scatterchart_material"></div>
To add to the answer of WhiteHat:
ScatterChart + Tooltip + Dashboard filter column:
I experienced with the ScatterChart that tooltips also do not work with the "arrayToDataTable method" IF there is also a string column that is used as the filter column of the google.visualization.ControlWrapper.
The "arrayToDataTable method" works well with just 2 columns with data and a 3rd column with the tooltip.
It also works well if the 3rd column contains the input for the dashboard filter.
But there is a 3rd and a 4th column then the "arrayToDataTable method" cannot be used (for ScatterCharts).
It works well if I use the DataTable.addRows method:
google.charts.setOnLoadCallback(chart_ecdf);
function chart_ecdf() {
var data = new google.visualization.DataTable();
data.addColumn('number','Population');
data.addColumn('number','Area');
data.addColumn({
type: 'string',
role: 'tooltip',
})
data.addColumn('string','Filter');
data.addRows([
[1324, 9640821, 'Annotated 1', 'A'],
[1133, 3287263, 'Annotated 2', 'A'],
[304, 9629091, 'Annotated 3', 'A'],
[232, 1904569, 'Annotated 4', 'B'],
[187, 8514877, 'Annotated 5', 'B']
]);
var filter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'filter_ecdf',
options: {
filterColumnIndex: 3,
ui: { caption: 'Kies een type', label: false, allowTyping: false, allowMultiple: false, allowNone: false, sortValues: false } },
state: {'selectedValues': ['{{ .Params.ecdf_filter_state | safeJS }}']}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ScatterChart',
containerId: 'grafiek_ecdf',
view: {columns: [0,1,2]},
options: {
chartArea: {top:10, left:35, width:'82%', height:'90%'},
vAxis: {minValue: 0, maxValue: 1, format: 'percent'},
hAxis: {format: '#.##%' },
legend: 'none',
colors: ['#ffa852'] },
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_ecdf'));
dashboard.bind(filter, chart);
dashboard.draw(data);
}

Google Charts area chart custom tooltip not working as expected

I'm trying to add tooltips to a Google Area Chart, but I'm getting unexpected behavior. I took the Area Chart JSFiddle example and modified it to add a custom tooltip as described here. My content looks like this:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', { type: 'string', role: 'tooltip'}],
['2013', 1000, 400, 'wtf'],
['2014', 1170, 460, 'hithere'],
['2015', 660, 1120, 'doh'],
['2016', 1030, 540, 'moohaha']
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
focusTarget: 'category'
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
JSFiddle here: https://jsfiddle.net/accelerate/y18tb8eq/
Rather than replacing the entire tooltip content, like I expected, the 'expenses' line in the tooltip gets replaced with my tooltip data. For example, the tooltip for the first set of data looks like:
2013
Sales: 1,000
Expenses: wtf
Can someone explain to me what I'm doing wrong?
I figured it out. Which column the tooltip is in matters. I needed to put the tooltip column immediately after the first column. So my header column has to look like this:
['Year', { type: 'string', role: 'tooltip'}, 'Sales', 'Expenses']

Google chart table formatting cell as percentage

I am trying to format a cell in a google chart table as a percentage field.
For a column it works with :
var flow_format2 = new google.visualization.NumberFormat( {suffix: '%', negativeColor: 'red', negativeParens: true, fractionDigits: 0} );
But as far as I can read there is no possibility for a row, therefore I would like to do it on cell level - is that possible?
Is it with setProperty I need to do it and what is the formatting syntax.
you can use the formatValue method of NumberFormat to get the formatted string
rather than applying to the entire column
then you can manually setFormattedValue on the DataTable cell
to change the color, use setProperty to change the cell's 'style' property
the chart must be drawn afterwards
--or--
when the chart's 'ready' event fires, you can change the cell value using the DOM
the Table chart produces a normal set of html <table> tags
following is a working snippet, demonstrating both approaches...
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable({
cols: [
{label: 'Name', type: 'string'},
{label: 'Amount', type: 'number'},
],
rows: [
{c:[{v: 'Adam'}, {v: -1201}]},
{c:[{v: 'Mike'}, {v: 2235}]},
{c:[{v: 'Stephen'}, {v: -5222}]},
{c:[{v: 'Victor'}, {v: 1288}]},
{c:[{v: 'Wes'}, {v: -6753}]}
]
});
var container = document.getElementById('chart_div');
var tableChart = new google.visualization.Table(container);
var patternFormat = {
suffix: '%',
negativeColor: '#FF0000',
negativeParens: true,
fractionDigits: 0
};
// create the formatter
var formatter = new google.visualization.NumberFormat(patternFormat);
// format cell - first row
dataTable.setFormattedValue(0, 1, formatter.formatValue(dataTable.getValue(0, 1)));
if (dataTable.getValue(0, 1) < 0) {
dataTable.setProperty(0, 1, 'style', 'color: ' + patternFormat.negativeColor + ';');
}
google.visualization.events.addOneTimeListener(tableChart, 'ready', function () {
// format cell via DOM - third row
var tableCell = container.getElementsByTagName('TR')[3].cells[1];
tableCell.innerHTML = formatter.formatValue(dataTable.getValue(2, 1));
if (dataTable.getValue(2, 1) < 0) {
tableCell.style.color = patternFormat.negativeColor;
}
});
tableChart.draw(dataTable, {
allowHtml: true
});
},
packages: ['table']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>