How to reload data in Google Charts Calendar while keeping selected cell? - javascript

I use jQuery and I use the following JS function to load and reload / redraw the Google Chart Calendar.
It works, however, it also removes the border from the selected item. I want to reload the calendar data, while keeping the currently selected item selected.
Any ideas?
function refreshCalendar( rows)
{
//if( calendar != 0 )
{
calendar = new google.visualization.Calendar(document.getElementById('calendar_basic'))
google.visualization.events.addListener(calendar, 'select', calendarSelectHandler);
calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows( rows );
calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
}
}

Normally, you would use chart.getSelection and chart.setSelection.
Get selection on 'select' event
Set selection on 'ready' event
getSelection works fine, but setSelection doesn't work with the Calendar chart.
No error is thrown, but nothing is selected.
I tried versions '41' thru 'current'...
To demonstrate, the following example uses both a Calendar chart and a Column chart.
Make a selection on both charts, then click "Redraw Chart".
The selection for the Column chart remains but not on the Calendar.
google.charts.load('current', {
callback: drawChart,
packages: ['calendar', 'corechart']
});
function drawChart() {
var selectionCal;
var selectionCol;
var calendar = new google.visualization.Calendar(document.getElementById('calendar'))
google.visualization.events.addListener(calendar, 'select', function () {
selectionCal = calendar.getSelection();
});
google.visualization.events.addListener(calendar, 'ready', function () {
if (selectionCal) {
calendar.setSelection(selectionCal);
}
});
var column = new google.visualization.ColumnChart(document.getElementById('column'))
google.visualization.events.addListener(column, 'select', function () {
selectionCol = column.getSelection();
});
google.visualization.events.addListener(column, 'ready', function () {
if (selectionCol) {
column.setSelection(selectionCol);
}
});
document.getElementById('test_button').addEventListener('click', function () {
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}, false);
var calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows([
[ new Date(2012, 3, 13), 37032 ],
[ new Date(2012, 3, 14), 38024 ],
[ new Date(2012, 3, 15), 38024 ],
[ new Date(2012, 3, 16), 38108 ],
[ new Date(2012, 3, 17), 38229 ],
]);
var calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="calendar"></div>
<div id="column"></div>
<input type="button" id="test_button" value="Redraw Chart" />

I can also confirm that the setSelection() method doesn't change anything on the UI for the calendar chart.
So I looked up what happens after selecting a day in the chart with the mouse. Then I implemented a simple DOM manipulation logic which does the same. You can use that logic as a replacement of the setSelection() use case. (It is just a quick prototype, but I hope it helps you, too).
For a litte demo I adjusted #WhiteHat snippet / the selected day survives now the refresh action (doesn't work with charts which needs to display more than one year!):
google.charts.load('current', {
callback: drawChart,
packages: ['calendar', 'corechart']
});
function drawChart() {
var selectionCal;
var selectionDate;
var selectionCol;
var calendar = new google.visualization.Calendar(document.getElementById('calendar'))
google.visualization.events.addListener(calendar, 'select', function () {
selectionCal = calendar.getSelection();
selectionDate = new Date(selectionCal[0].date);
});
google.visualization.events.addListener(calendar, 'ready', function () {
if (selectionDate) {
// google calendar setSelection BUG :/
// https://stackoverflow.com/a/36093217/810944
// do it manually
var doy = selectionDate.getDOY();
markDayInChart(doy);
}
});
var column = new google.visualization.ColumnChart(document.getElementById('column'))
google.visualization.events.addListener(column, 'select', function () {
selectionCol = column.getSelection();
});
google.visualization.events.addListener(column, 'ready', function () {
if (selectionCol) {
column.setSelection(selectionCol);
}
});
document.getElementById('test_button').addEventListener('click', function () {
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}, false);
var calendarData = new google.visualization.DataTable();
calendarData.addColumn({ type: 'date', id: 'Date' });
calendarData.addColumn({ type: 'number', id: 'Logs' });
calendarData.addRows([
[ new Date(2012, 3, 13), 37032 ],
[ new Date(2012, 3, 14), 38024 ],
[ new Date(2012, 3, 15), 38024 ],
[ new Date(2012, 3, 16), 38108 ],
[ new Date(2012, 3, 17), 38229 ],
]);
var calendarOptions = {
title: "Logs",
height: 175,
colorAxis: {minValue: 0, colors: ['#FFFFFF', '#FF0000']},
calendar: {
focusedCellColor: {
background: '#00FF00',
stroke: '#004400',
strokeOpacity: 1,
strokeWidth: 2,
},
cellColor: {
stroke: '#76a7fa',
strokeOpacity: 0.5,
strokeWidth: 1,
}
}
};
calendar.draw(calendarData, calendarOptions);
column.draw(calendarData, {});
}
function markDayInChart(dayOfYear) {
// clones the logic for clicking / selecting a day via mouse
// keep in mind to clean up the adjusted and added `rect`-elements if you do not use full page reloads!
// doesn't work with charts which needs to display more than one year!
var days_all_svg_group = $('#calendar svg').children('g')[1];
var days_marked_svg_group = $('#calendar svg').children('g')[4];
var day_svg_rect = $('rect:nth-of-type('+dayOfYear+')',$(days_all_svg_group));
// hide the original rect
$(day_svg_rect).css('display: none;');
// add a cloned rect with a different stroke
var day_marked_svg_rect = $(day_svg_rect).clone();
$(day_marked_svg_rect).attr({stroke: '#000000', 'stroke-width': 2});
$(day_marked_svg_rect).attr('stroke-opacity', null);
$(days_marked_svg_group).append(day_marked_svg_rect);
}
// https://stackoverflow.com/a/26426761/810944
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if((year & 3) != 0) return false;
return ((year % 100) != 0 || (year % 400) == 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = this.getMonth();
var dn = this.getDate();
var dayOfYear = dayCount[mn] + dn;
if(mn > 1 && this.isLeapYear()) dayOfYear++;
return dayOfYear;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="calendar"></div>
<div id="column"></div>
<input type="button" id="test_button" value="Redraw Chart" />

Related

Google Chart Resize on Window Resize

How can I get my google chart to resize properly, currently it gets bigger when I expand the window but it does not shrink when i shrink the window. Essentially I've wrapped the entire google chart in a resize function but it isn't quite right:
function resize() {
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Type' });
dataTable.addColumn({ type: 'string', id: 'Organisation' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'Work Experience', 'GE', new Date(2010, 8, 1 ), new Date(2011, 8, 30) ],
[ 'Work Experience', 'Shell', new Date(2015, 2, 1), new Date(2016, 1, 1) ],
[ 'Work Experience', 'British Gas', new Date(2016, 1, 1), new Date(2017, 9, 1) ],
[ 'Work Experience', 'British Telecom', new Date(2017, 9, 1), new Date() ],
[ 'Work Experience', 'University', new Date(2011, 8, 30), new Date(2015, 2,1) ]
]);
var options = {
timeline: {showRowLabels: false},
backgroundColor: '#161616',
barLabelStyle: { fontName: 'Roboto', color: '#ffffff' },
height: 100,
hAxis: {textStyle:{color: '#ffffff'}}
};
google.visualization.events.addListener(chart, 'ready', function () {
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
if (label.getAttribute('text-anchor') === 'middle') {
label.setAttribute('fill', '#ffffff');
}
});
});
google.visualization.events.addListener(chart, 'ready', function () {
var rects = container.getElementsByTagName('rect');
Array.prototype.forEach.call(rects, function(rect) {
// find chart <rect> element
if ((rect.getAttribute('x') === '0') && (rect.getAttribute('y') === '0')) {
// remove stroke from last <rect> element
rect.setAttribute('stroke', 'none');
rect.setAttribute('stroke-width', '0');
}
});
});
chart.draw(dataTable, options);
}
}
window.onload = resize;
window.onresize = resize;
when resizing, you need to clear the chart, before re-drawing.
if the chart is not cleared, it can prevent the chart's container from shrinking.
then when re-drawn, it is the same size.
(this all depends on the page layout, but clearing will resolve most issues)
use method --> chart.clearChart()
also, the load callback only needs to be called once per page load.
no need to include the load statement in the resize event handler.
and, google's load statement will wait for the page to load by default.
and can be used in place of --> window.onload
see following working snippet...
google.charts.load('current', {
packages: ['timeline']
}).then(function () {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Type' });
dataTable.addColumn({ type: 'string', id: 'Organisation' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
['Work Experience', 'GE', new Date(2010, 8, 1 ), new Date(2011, 8, 30)],
['Work Experience', 'Shell', new Date(2015, 2, 1), new Date(2016, 1, 1)],
['Work Experience', 'British Gas', new Date(2016, 1, 1), new Date(2017, 9, 1)],
['Work Experience', 'British Telecom', new Date(2017, 9, 1), new Date()],
['Work Experience', 'University', new Date(2011, 8, 30), new Date(2015, 2,1)]
]);
var options = {
timeline: {showRowLabels: false},
backgroundColor: '#161616',
barLabelStyle: {fontName: 'Roboto', color: '#ffffff'},
height: 100,
hAxis: {textStyle:{color: '#ffffff'}}
};
google.visualization.events.addListener(chart, 'ready', function () {
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
if (label.getAttribute('text-anchor') === 'middle') {
label.setAttribute('fill', '#ffffff');
}
});
var rects = container.getElementsByTagName('rect');
Array.prototype.forEach.call(rects, function(rect) {
// find chart <rect> element
if ((rect.getAttribute('x') === '0') && (rect.getAttribute('y') === '0')) {
// remove stroke from last <rect> element
rect.setAttribute('stroke', 'none');
rect.setAttribute('stroke-width', '0');
}
});
});
window.addEventListener('resize', drawChart);
drawChart();
function drawChart() {
chart.clearChart();
chart.draw(dataTable, options);
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>

Remove borders and gridlines around google chart timeline

I need to remove the border and the gridlines from the google charts timetable (see documentation)
Right now it looks like this: with borders
It should look like this: without borders
I made a stackblitz for it: https://stackblitz.com/edit/js-ozv5hr?file=index.html
It seems like the config options that you can use for example with line charts do not work with timelines.
there are no config options available for removing the borders,
but we can remove them manually on the chart's 'ready' event.
see following working snippet...
google.charts.load("current", {
packages: ["timeline"]
}).then(function () {
var container = document.getElementById("timeline");
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: "string", id: "Label" });
dataTable.addColumn({ type: "string", id: "Type" });
dataTable.addColumn({ type: "date", id: "Start" });
dataTable.addColumn({ type: "date", id: "End" });
dataTable.addRows([
["A", "A", new Date(2021, 0, 0, 0), new Date(2021, 0, 0, 1)],
["A", "B", new Date(2021, 0, 0, 1), new Date(2021, 0, 0, 2)],
["A", "C", new Date(2021, 0, 0, 2), new Date(2021, 0, 0, 3)]
]);
var options = {
timeline: {
groupByRowLabel: true,
showRowLabels: false,
showBarLabels: false
},
avoidOverlappingGridLines: false,
hAxis: {
format: "HH:mm"
},
gridlines: {
color: "none"
}
};
google.visualization.events.addListener(chart, 'ready', function () {
// find <rect> elements
var rects = container.getElementsByTagName('rect');
Array.prototype.forEach.call(rects, function(rect) {
if (rect.getAttribute('stroke') === '#9a9a9a') {
// remove border
rect.setAttribute('stroke-width', '0');
}
});
// find <path> elements
var paths = container.getElementsByTagName('path');
Array.prototype.forEach.call(paths, function(path) {
if ((path.getAttribute('stroke') === '#ffffff') || (path.getAttribute('stroke') === '#e6e6e6')) {
// remove border
path.setAttribute('stroke-width', '0');
}
});
});
chart.draw(dataTable, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>

Google Charts: Problem handling a 'click' event

I have a Google Chart, a bar chart, that I recently extended so that selecting one of the bars will open a new page, showing the data corresponding to that bar. I used the guidelines for basic interactivity, using a selectHandler to process the event.
I then decided to do the same thing when clicking on one of the labels, but I have not been able to get this to work. I looked pretty carefully at the docs, and at this older question (which is, in fact, my actual question: how do I make a hyperlink out of the chart's labels?) for guidance. I added a Listener for click events, and a handler for this, but my chart is not responding to them.
My basic setup is:
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
var books = [
['2018-07', 5, 98.0],
['2018-08', 5, 100.0], // etc.
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Number Purchased');
data.addColumn('number', 'Price Paid');
data.addRows(books);
var options = {
chart: {
title: 'Book Purchases',
},
width: 800,
height: 800,
bars: 'horizontal',
series: {
0: {
axis: 'purchased'
},
1: {
axis: 'price_paid'
}
},
axes: {
x: {
purchased: {
side: 'top',
label: 'Number Purchased'
},
price_paid: {
label: 'Price Paid'
}
}
}
};
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var date = data.getValue(selectedItem.row, 0);
var query_string = '?date=' + date;
var path = window.location.pathname;
path = path.replace("bookgraph", "");
path = path + "search" + query_string;
var newURL = window.location.protocol + "//" + window.location.host + path;
window.open(newURL, '_blank');
}
}
function clickHandler(e) {
alert('The user has clicked on ' + e.targetID);
}
var chart = new google.charts.Bar(document.getElementById('bookgraph_material'));
google.visualization.events.addListener(chart, 'click', clickHandler);
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
The selectHandler works fine. But I can't even get the clickHandler to show the alert (after this works, I'll actually code the rest of it); it's apparently never fired, regardless of where I click. What am I doing wrong?
I set up a JS Fiddle page for this, to experiment with, with an HTML frame so it'll actually work; this shows the working select (albeit to a 404, of course) and the nonworking click.
Thanks.
the 'click' event is not supported by Material charts,
see issue #: 2257...
and there are several configuration options that are not supported as well,
see issue #: 2143...
Material = google.charts.Bar -- packages: ['bar']
Classic = google.visualization.BarChart -- packages: ['corechart']
one work around would be to use a Classic chart with option --> theme: 'material'
or register your own click event,
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['bar']
});
var books = [
['2016-01', 3, 45.0],
['2016-02', 3, 56.0],
['2016-03', 1, 23.0],
['2016-04', 4, 60.0],
['2016-05', 1, 0],
['2016-06', 3, 14.0],
['2016-07', 4, 65.0],
['2016-08', 1, 15.0],
['2016-09', 13, 234.0],
['2016-10', 20, 834.0],
['2016-11', 5, 115.0],
['2016-12', 5, 58.0],
['2017-01', 6, 122.0],
['2017-02', 4, 84.0],
['2017-03', 1, 0],
['2017-04', 1, 30.0],
['2017-05', 2, 38.0],
['2017-06', 1, 11.0],
['2017-07', 0, 0],
['2017-08', 4, 88.0],
['2017-09', 5, 89.0],
['2017-10', 4, 73.0],
['2017-11', 5, 79.0],
['2017-12', 2, 37.0],
['2018-01', 1, 22.0],
['2018-02', 5, 98.0],
['2018-03', 5, 132.0],
['2018-04', 3, 56.0],
['2018-05', 14, 272.0],
['2018-06', 4, 88.0],
['2018-07', 5, 98.0],
['2018-08', 5, 100.0],
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Number Purchased');
data.addColumn('number', 'Price Paid');
data.addRows(books);
var options = {
chart: {
title: 'Book Purchases',
},
width: 800,
height: 800,
bars: 'horizontal',
series: {
0: {
axis: 'purchased'
},
1: {
axis: 'price_paid'
}
},
axes: {
x: {
purchased: {
side: 'top',
label: 'Number Purchased'
},
price_paid: {
label: 'Price Paid'
}
}
}
};
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var date = data.getValue(selectedItem.row, 0);
var query_string = '?date=' + date;
var path = window.location.pathname;
path = path.replace("bookgraph", "");
path = path + "search" + query_string;
var newURL = window.location.protocol + "//" + window.location.host + path;
window.open(newURL, '_blank');
}
}
function clickHandler(e) {
if (e.target.tagName === 'text') {
console.log(e.target.textContent);
}
}
var container = document.getElementById('bookgraph_material');
var chart = new google.charts.Bar(container);
google.visualization.events.addListener(chart, 'select', selectHandler);
container.addEventListener('click', clickHandler);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="bookgraph_material"></div>

Google Timeline Visualization doesn't change series row height on slider interaction

So I've got a timeline with data in it that can be concurrent...
When I move the ChartRangeSlider to a different timeframe, some of the timeline bars will either disappear or show because there is nothing happening in the timeframe that is active.
These is how the timeline and the range slider are set up. I don't have any event listeners running...
// Configure range slider
var timelineRangeSlider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'timeline-filter',
'state':
{
'range':
{
'start': currentTime,
'end': fourWeek
}
},
'options':
{
'filterColumnIndex': 4,
'ui':
{
'chartType': 'ScatterChart',
'chartOptions':
{
'width': '100%',
'height': '50',
'chartArea':
{
'width': '80%', // make sure this is the same for the chart and control so the axes align right
'height': '80%'
},
'hAxis':
{
'baselineColor': 'none'
}
},
'chartView':
{
'columns': [4,6]
}
}
}
});
// Configure timeline
var timeline = new google.visualization.ChartWrapper({
'chartType': 'Timeline',
'containerId': 'timeline-chart',
'options':
{
'timeline':
{
'showBarLabels': false
},
'width': '100%',
'height': '325',
'tooltip':
{
'isHtml': true
},
'chartArea':
{
'width': '80%', // make sure this is the same for the chart and control so the axes align right
'height': '80%'
},
},
'view':
{
'columns': [0,1,2,3,4,5]
}
});
How can I stop this from happening, and have each of the four separate rows (one for each series) have a static height that won't change when I interact with the range slider?
to display the same number of rows, regardless of the filter settings,
replace the rows removed by the filter with "blank" rows,
doing so will require some manipulation
if you're using a dashboard to bind the chart and filter,
it will probably be easier to draw each independently
listen for the 'statechange' event on the filter,
to know when to re-draw the chart
use a data view to exclude the rows hidden by the filter,
add blank rows in their place
use the colors option on the timeline to set blank rows to 'transparent'
also use a blank tooltip for these rows
see following working snippet, for an example of how this could be accomplished...
google.charts.load('current', {
packages: ['controls', 'timeline']
}).then(function () {
var dataTable = google.visualization.arrayToDataTable([
['Row Label', 'Bar Label', {role: 'tooltip', type: 'string', p: {html: true}}, 'Start', 'End', 'Scatter', 'Data / Blank'],
['A', 'Series 0', null, new Date(2018, 1, 1), new Date(2018, 1, 28), 1, 'data'],
['B', 'Series 1', null, new Date(2018, 4, 1), new Date(2018, 4, 31), 1, 'data'],
['C', 'Series 2', null, new Date(2018, 7, 1), new Date(2018, 7, 31), 1, 'data'],
['D', 'Series 3', null, new Date(2018, 10, 1), new Date(2018, 10, 30), 1, 'data']
]);
var blankTooltip = '<div class="hidden"></div>';
var colorPallette = ['cyan', 'magenta', 'lime', 'yellow'];
var dateRange = {
start: dataTable.getColumnRange(3),
end: dataTable.getColumnRange(4)
};
// Configure range slider
var timelineRangeSlider = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'timeline-filter',
dataTable: dataTable,
state: {
range: {
start: dateRange.start.min,
end: dateRange.end.max
}
},
options: {
filterColumnIndex: 3,
ui: {
chartType: 'ScatterChart',
chartOptions: {
width: '100%',
height: '50',
chartArea: {
width: '80%',
height: '80%'
},
hAxis: {
baselineColor: 'none'
}
},
chartView: {
columns: [3,5]
}
}
}
});
google.visualization.events.addListener(timelineRangeSlider, 'statechange', function (props) {
// filter state
var state = timelineRangeSlider.getState();
// wait until statechange has finished
if (!props.inProgress) {
// delete previously added blank rows
var blankRows = dataTable.getFilteredRows([{
column: 6,
value: 'blank'
}]);
var i = blankRows.length;
while (i--) {
dataTable.removeRow(blankRows[i]);
}
// add blank rows for non-visible rows
var blankRows = [];
var timelineColors = [];
var visibleRows = dataTable.getFilteredRows([{
column: 3,
minValue: state.range.start
}, {
column: 4,
maxValue: state.range.end
}]);
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
if (visibleRows.indexOf(i) === -1) {
blankRows.push([
dataTable.getValue(i, 0),
dataTable.getValue(i, 1),
blankTooltip,
state.range.start,
state.range.start,
1,
'blank'
]);
timelineColors.push('transparent');
} else {
timelineColors.push(colorPallette[i]);
}
}
// build timeline view rows
var lastRowIndex = dataTable.addRows(blankRows);
var i = blankRows.length;
while (i--) {
visibleRows.push((lastRowIndex - i));
}
// re-config timeline
var timelineView = new google.visualization.DataView(dataTable);
timelineView.setRows(visibleRows);
timelineView = timelineView.toDataTable();
timelineView.sort([{column: 0}]);
timeline.setDataTable(timelineView);
timeline.setOption('colors', timelineColors);
timeline.draw();
}
});
timelineRangeSlider.draw();
// Configure timeline
var timeline = new google.visualization.ChartWrapper({
chartType: 'Timeline',
containerId: 'timeline-chart',
dataTable: dataTable,
options: {
colors: colorPallette,
timeline: {
showBarLabels: false
},
width: '100%',
height: '325',
tooltip: {
isHtml: true
},
chartArea: {
width: '80%',
height: '80%'
}
},
view: {
columns: [0,1,2,3,4]
}
});
timeline.draw();
});
.hidden {
display: none;
visibility: hidden;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<div id="timeline-filter"></div>
<div id="timeline-chart"></div>
</div>

Google Timeline Chart Change HAxis to string value

I would like to ask if it is possible that the haxis value (The one with dates below) for Google Timeline change to string format?
For example, Oct. 30 will be changed to Week 1, Nov. 6 to Week 2, and so on.
Any help and suggestions are welcomed and appreciated.
Thanks in advance!
the timeline chart is very limited compared to the core charts
both in terms of options available and helper methods for finding chart coordinates, etc...
but like core charts, timelines produce svg, which can be modified using javascript
see following working snippet...
once the chart's 'ready' event fires, all of the haxis labels are removed
then custom labels are added back for the week numbers
before removing all the labels, one is cloned, in order to keep the same font, color, y-coordinate, etc...
then the timeline bars are used to find the x-coordinate and add the new label
google.charts.load('current', {
callback: function () {
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'string', id: 'Category'});
dataTable.addColumn({type: 'date', id: 'Start'});
dataTable.addColumn({type: 'date', id: 'End'});
dataTable.addRows([
['Category A', new Date(2016, 9, 30), new Date(2016, 10, 5)],
['Category B', new Date(2016, 10, 6), new Date(2016, 10, 12)],
['Category C', new Date(2016, 10, 13), new Date(2016, 10, 19)]
]);
google.visualization.events.addListener(chart, 'ready', function () {
var rowIndex = 0; // data table row index
var weekLabel = null; // clone of text node - keep font settings, y-coord, etc...
// remove haxis labels
var labels = container.getElementsByTagName('text');
while (labels.length > dataTable.getNumberOfRows()) {
// ignore "category" labels
if (dataTable.getFilteredRows([{column: 0, value: labels[labels.length - 1].innerHTML}]).length === 0) {
if (weekLabel === null) {
weekLabel = labels[labels.length - 1].cloneNode(true);
}
labels[labels.length - 1].parentNode.removeChild(labels[labels.length - 1]);
}
}
// use timeline bars to find x coordinate for week labels
rowIndex = 0;
var svgParent = container.getElementsByTagName('svg')[0];
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(bar) {
var bounds; // bounding box of text element
// ignore rect if not a timeline bar
if (parseFloat(bar.getAttribute('x')) > 0) {
weekLabel = weekLabel.cloneNode(true);
weekLabel.innerHTML = 'Week ' + (rowIndex + 1);
svgParent.appendChild(weekLabel);
bounds = weekLabel.getBBox();
weekLabel.setAttribute('x', parseFloat(bar.getAttribute('x')) + bounds.width);
rowIndex++;
}
});
});
chart.draw(dataTable);
},
packages:['timeline']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
google.charts.load("current", {packages:["timeline"], callback: drawChart});
function drawChart() {
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
// hAxis put on top
google.visualization.events.addListener(chart, 'ready', afterDraw);
// Link in tooltip
google.visualization.events.addListener(chart, 'select', function(e) {
var tooltip = document.querySelector('.google-visualization-tooltip:not([clone])');
if (chart.ttclone) {
chart.ttclone.parentNode.removeChild(chart.ttclone)
}
chart.ttclone = tooltip.cloneNode(true);
chart.ttclone.setAttribute('clone', true);
chart.ttclone.style.pointerEvents = 'auto';
tooltip.parentNode.insertBefore(chart.ttclone, chart.tooltip);
});
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Name' });
// for colorMap
dataTable.addColumn({ type: 'string', id: 'Course' });
dataTable.addColumn({ type: 'string', id: 'Subject' });
dataTable.addColumn({ type: 'string', id: 'ToolTip', role: 'tooltip', p:{html:true} });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
// Timeline Start
['Student 1', 'ENGR', 'Trigonometry', 'Trigonometry', new Date(2016, 9, 30), new Date(2016, 10, 06)],
['Student 2', 'IT', 'DB Management', 'DB Management', new Date(2016, 9, 30), new Date(2016, 10, 13)],
['Student 3', 'CS', 'Introduction to Programming', 'Introduction to Programming', new Date(2016, 9, 30), new Date(2016, 10, 27)],
]);
var colors = [];
var colorMap = {
ENGR: '#2ECC71', // Green
IT: '#E67E22', // Brown
CS: '#9B59B6', // Violet
}
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
colors.push(colorMap[dataTable.getValue(i, 1)]);
}
var rowHeight = 41;
var chartHeight = (dataTable.getNumberOfRows() + 1) * rowHeight;
var options = {
timeline: {
groupByRowLabel: true,
rowLabelStyle: {
fontName: 'Century Gothic',
fontSize: 14,
color: '#333333',
bold: 'true',
},
barLabelStyle: {
fontName: 'Century Gothic',
fontSize: 11,
},
showRowLabels: true,
showBarLabels: true,
},
hAxis: {
minValue: new Date(2016, 9, 30),
maxValue: new Date(2017, 9, 28),
},
avoidOverlappingGridLines: true,
height: chartHeight,
width: '100%',
colors: colors,
};
// use a DataView to hide the category column from the Timeline
var view = new google.visualization.DataView(dataTable);
view.setColumns([0, 2, 3, 4, 5]);
// Change HAxis labels to Week
google.visualization.events.addListener(chart, 'ready', function () {
var rowIndex = 0; // data table row index
var weekLabel = null; // clone of text node - keep font settings, y-coord, etc...
// remove haxis labels
var labels = container.getElementsByTagName('text');
while (labels.length > dataTable.getNumberOfRows()) {
// ignore "category" labels
if (dataTable.getFilteredRows([{column: 5, value: labels[labels.length - 1].innerHTML}]).length === 0) {
if (weekLabel === null) {
weekLabel = labels[labels.length - 1].cloneNode(true);
}
labels[labels.length - 1].parentNode.removeChild(labels[labels.length - 1]);
}
}
// use timeline bars to find x coordinate for week labels
rowIndex = 0;
var svgParent = container.getElementsByTagName('svg')[0];
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(bar) {
var bounds; // bounding box of text element
// ignore rect if not a timeline bar
if (parseFloat(bar.getAttribute('x')) > 0) {
weekLabel = weekLabel.cloneNode(true);
weekLabel.innerHTML = 'WW 70' + (rowIndex + 1);
svgParent.appendChild(weekLabel);
bounds = weekLabel.getBBox();
weekLabel.setAttribute('x', parseFloat(bar.getAttribute('x')) + bounds.width);
rowIndex++;
}
});
});
chart.draw(
view,
options,
dataTable, {
tooltip: {
isHtml: true,
},
timeline: {
showBarLabels: false,
}
});
}
// hAxis put on top
function afterDraw() {
var g = document.getElementsByTagName("svg")[0].getElementsByTagName("g")[1];
document.getElementsByTagName("svg")[0].parentNode.style.top = '40px';
document.getElementsByTagName("svg")[0].style.overflow = 'visible';
var height = Number(g.getElementsByTagName("text")[0].getAttribute('y')) + 15;
g.setAttribute('transform','translate(0,-'+height+')');
g = null;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Categories

Resources