Related
I'm new to coding but over the last several months I've managed to fumble my way through creating a web site that utilises a Google Line Chart and embedded linear trendline to display historical Mean Sea Level and the rate of Mean Sea Level rise for various locations around New Zealand and the Pacific. Each location has it's own Google Line Chart with a linear trendline to show the rate of Mean Sea Level Change for a user selected period. I now want to extend the functionality of each Google Line Chart such that both a linear and polynomial trendline extend to the year 2120 (they currently only show up to the year 2018) even though the available data from which they are calculated uses observed data up to the year 2018. This will allow the user to predict the sea level height up to the year 2020. I realise this explanation may be confusing, so please see my web site www.sealevel.nz to see the existing charts which I hope will aid in understanding my problem.
Below is the code for the extended version of the chart that shows both a linear and second degree polynomial trendline with the x axis of the Google Line Chart now showing up the year 2120. My problem is that I need the y axis to adjust dynamically to show the entirety of both trendlines no matter which time period the user selects. For example if you select the years 1971 and 2018 from the date range slider, then both trendlines are cut off at the years 2017 (linear) and 2031 (polynomial) respectively. I need to be able to see both trendlines and their values up to the year 2120.
Please excuse my novice coding skills. My Code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://unpkg.com/mathjs/dist/math.min.js"></script>
<script type="text/javascript">
google.load('visualization', 'current', {'packages':['controls','corechart']});
google.setOnLoadCallback(initialize);
function initialize() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1vn1iuhsG33XzFrC4QwkTdUnxOGdcPQOj-cuaEZeX-eA/edit#gid=0');
query.send(drawDashboard);
}
function drawDashboard(response) {
var data = response.getDataTable();
//Asign units of 'mm' to data.
var formatMS = new google.visualization.NumberFormat({
pattern: '# mm'
});
// format into data mm..
for (var colIndex = 1; colIndex < data.getNumberOfColumns(); colIndex++) {
formatMS.format(data, colIndex);
}
var YearPicker = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Year',
'ui': {
cssClass: 'filter-date',
'format': { pattern: '0000' },
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
},
});
var MSLChart = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'chart_div',
'options': {
'fontSize': '14',
'title': 'Timbucktoo Annual Mean Sea Level Summary',
hAxis: {title: 'Year', format:'0000', maxValue: 2120},
vAxis: {title: 'Height above Chart Datum (mm)', format:'0000'},
'height': 600,
chartArea: {height: '81%', width: '85%', left: 100},
'legend': {'position': 'in', 'alignment':'end', textStyle: {fontSize: 13} },
colors: ['blue'],
trendlines: {
0: {
type: 'polynomial',
degree: 2,
color: 'green',
visibleInLegend: true,
},
1: {
type: 'linear',
color: 'black',
visibleInLegend: true,
},
},
series: {
0: { visibleInLegend: true },
1: { visibleInLegend: false },
},
},
'view': {'columns': [0,1,2]}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div')).
bind(YearPicker, MSLChart).
draw(data)
</script>
first, I'm not sure why the chart would draw a trend line that isn't visible
which makes this a bit tricky, because we first have to draw the chart,
in order to find the min & max y-axis values.
but there are chart methods we can use to find the max value.
first, we get the chart's layout interface.
var chartLayout = MSLChart.getChart().getChartLayoutInterface();
since we're using a ChartWrapper, we have to get the chart from the wrapper (MSLChart.getChart()).
next, we use method getBoundingBox to find the min & max values of each line.
var yAxisCoords = {min: null, max: null};
var lineIndex = 0;
var boundsLine = chartLayout.getBoundingBox('line#' + lineIndex);
do {
yAxisCoords.max = yAxisCoords.max || boundsLine.top;
yAxisCoords.max = Math.min(yAxisCoords.max, boundsLine.top);
yAxisCoords.min = yAxisCoords.min || (boundsLine.top + boundsLine.height);
yAxisCoords.min = Math.max(yAxisCoords.min, (boundsLine.top + boundsLine.height));
lineIndex++;
boundsLine = chartLayout.getBoundingBox('line#' + lineIndex);
} while (boundsLine !== null);
then we use method getVAxisValue to determine what each y-axis value should be,
set the viewWindow on the y-axis, and re-draw the chart.
MSLChart.setOption('vAxis.viewWindow.max', chartLayout.getVAxisValue(yAxisCoords.max));
MSLChart.setOption('vAxis.viewWindow.min', chartLayout.getVAxisValue(yAxisCoords.min));
MSLChart.draw();
we do all this in a function.
we use a one time 'ready' event on the chart wrapper for the first calculation.
then again, on the chart.
google.visualization.events.addOneTimeListener(MSLChart, 'ready', filterChange);
function filterChange() {
// get chart layout
var chartLayout = MSLChart.getChart().getChartLayoutInterface();
// get y-axis bounds
var yAxisCoords = {min: null, max: null};
var lineIndex = 0;
var boundsLine = chartLayout.getBoundingBox('line#' + lineIndex);
do {
yAxisCoords.max = yAxisCoords.max || boundsLine.top;
yAxisCoords.max = Math.min(yAxisCoords.max, boundsLine.top);
yAxisCoords.min = yAxisCoords.min || (boundsLine.top + boundsLine.height);
yAxisCoords.min = Math.max(yAxisCoords.min, (boundsLine.top + boundsLine.height));
lineIndex++;
boundsLine = chartLayout.getBoundingBox('line#' + lineIndex);
} while (boundsLine !== null);
// re-draw chart
MSLChart.setOption('vAxis.viewWindow.max', chartLayout.getVAxisValue(yAxisCoords.max));
MSLChart.setOption('vAxis.viewWindow.min', chartLayout.getVAxisValue(yAxisCoords.min));
MSLChart.draw();
google.visualization.events.addOneTimeListener(MSLChart.getChart(), 'ready', filterChange);
}
see following working snippet...
(when you run the snippet, click "full page" at the top right)
google.charts.load('current', {
packages: ['controls']
}).then(initialize);
function initialize() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1vn1iuhsG33XzFrC4QwkTdUnxOGdcPQOj-cuaEZeX-eA/edit#gid=0');
query.send(drawDashboard);
}
function drawDashboard(response) {
var data = response.getDataTable();
//Asign units of 'mm' to data.
var formatMS = new google.visualization.NumberFormat({
pattern: '# mm'
});
// format into data mm..
for (var colIndex = 1; colIndex < data.getNumberOfColumns(); colIndex++) {
formatMS.format(data, colIndex);
}
var YearPicker = new google.visualization.ControlWrapper({
controlType: 'NumberRangeFilter',
containerId: 'filter_div',
options: {
filterColumnLabel: 'Year',
ui: {
cssClass: 'filter-date',
format: {pattern: '0000'},
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: false
}
},
});
var MSLChart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
dataTable: data,
options: {
fontSize: '14',
title: 'Timbucktoo Annual Mean Sea Level Summary',
hAxis: {title: 'Year', format: '0000', maxValue: 2120},
vAxis: {title: 'Height above Chart Datum (mm)', format:'###0'},
height: 600,
chartArea: {height: '81%', width: '85%', left: 100},
legend: {position: 'in', alignment: 'end', textStyle: {fontSize: 13}},
colors: ['blue'],
trendlines: {
0: {
type: 'polynomial',
degree: 2,
color: 'green',
visibleInLegend: true,
},
1: {
type: 'linear',
color: 'black',
visibleInLegend: true,
},
},
series: {
0: { visibleInLegend: true },
1: { visibleInLegend: false },
},
},
view: {columns: [0,1,2]}
});
google.visualization.events.addOneTimeListener(MSLChart, 'ready', filterChange);
function filterChange() {
// get chart layout
var chartLayout = MSLChart.getChart().getChartLayoutInterface();
// get y-axis bounds
var yAxisCoords = {min: null, max: null};
var lineIndex = 0;
var boundsLine = chartLayout.getBoundingBox('line#' + lineIndex);
do {
yAxisCoords.max = yAxisCoords.max || boundsLine.top;
yAxisCoords.max = Math.min(yAxisCoords.max, boundsLine.top);
yAxisCoords.min = yAxisCoords.min || (boundsLine.top + boundsLine.height);
yAxisCoords.min = Math.max(yAxisCoords.min, (boundsLine.top + boundsLine.height));
lineIndex++;
boundsLine = chartLayout.getBoundingBox('line#' + lineIndex);
} while (boundsLine !== null);
// re-draw chart
MSLChart.setOption('vAxis.viewWindow.max', chartLayout.getVAxisValue(yAxisCoords.max));
MSLChart.setOption('vAxis.viewWindow.min', chartLayout.getVAxisValue(yAxisCoords.min));
MSLChart.draw();
google.visualization.events.addOneTimeListener(MSLChart.getChart(), 'ready', filterChange);
}
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div')
).bind(YearPicker, MSLChart).draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<div id="chart_div"></div>
<div id="filter_div"></div>
</div>
note: it appears you're using an old load statement, to load google chart.
see above snippet for update...
I have been doing lot research on this memory leak in Google charts library. Didnt found any thing thats helping my situation. Not sure whats the updates on this one so far. I saw google chart dev team is trying to fix it and release a new updates.
I'm using line chart and the data is coming from websockets. which is constantly updating.
Thanks in advance
P.S below is the code I use to getting data from websockets. when the socket is connected the drawChart function is called every second. Meaning the whole line chart is redrawn
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'data');
data.addColumn('number', 'date');
var data_test = new google.visualization.DataTable();
data_test.addColumn('string', 'data test');
data_test.addColumn('number', 'date test');
for(var i=0; i<valueArr.length; i+=2) {
if (i>=120) {
data.removeRow(0);
valueArr.splice(0, 2);
timeArr.splice(0, 2);
}
data.addRow([timeArr[i], valueArr[i]]);
}
for(var i=1; i<valueArr.length; i+=2) {
if (i>=120) {
data_test.removeRow(0);
valueArr.splice(0, 2);
timeArr.splice(0, 2);
}
data_test.addRow([timeArr[i], valueArr[i]]);
}
//console.log(valueArr);
// use a DataView to 0-out all the values in the data set for the initial draw
var view = new google.visualization.DataView(data);
var view_test = new google.visualization.DataView(data_test);
// Create and draw the plot
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
var chart_test = new google.visualization.LineChart(document.getElementById('visualization_test'));
var options = {
title:" ",
width: 960,
height: 460,
bar: { groupWidth: "40%" },
legend: { position: "bottom" },
animation: {"startup": true},
curveType: 'function',
lineWidth: 3,
backgroundColor: '#f9f9f9',
colors: ['red'],
tooltip: {
textStyle: {
color: 'red',
italic: true
},
showColorCode: true
},
animation: {
startup: true,
easing: 'inAndOut',
//duration: 500
},
vAxis: {
title: '',
gridlines: {
count: 8,
color: '#999'
}
/*minValue: 1.3,
maxValue: 1.4*/
},
hAxis: {
title: 'Time Stamp'
},
};
//stay in sockets
var runOnce = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runOnce);
chart.draw(data, options);
chart_test.draw(data, options);
});
chart.draw(view, options);
chart_test.draw(view_test, options);
}
function init() {
try {
socket = new WebSocket(portal);
//console.log('WebSocket status '+socket.readyState);
socket.onopen = function(msg) {
//console.log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
parseData(msg);
drawVisualization();
};
socket.onclose = function(msg) {
console.log("Disconnected - status "+this.readyState);
};
}
catch(ex){
console.log(ex);
}
}
beginning with drawing only one chart, you might setup similar to following snippet...
this should draw the same chart with new data, only after the previous draw has finished...
function init() {
var getData = true;
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'ready', function () {
getData = true;
});
var options = {
title:" ",
width: 960,
height: 460,
bar: { groupWidth: "40%" },
legend: { position: "bottom" },
animation: {"startup": true},
curveType: 'function',
lineWidth: 3,
backgroundColor: '#f9f9f9',
colors: ['red'],
tooltip: {
textStyle: {
color: 'red',
italic: true
},
showColorCode: true
},
animation: {
startup: true,
easing: 'inAndOut',
//duration: 500
},
vAxis: {
title: '',
gridlines: {
count: 8,
color: '#999'
}
/*minValue: 1.3,
maxValue: 1.4*/
},
hAxis: {
title: 'Time Stamp'
},
};
// if you want data from previous draws, declare here...
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Value');
// or see below...
// msg = object with arrays from parseData
function drawVisualization(msg) {
// if you ** don't ** want data from previous draws, declare here instead...
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time');
data.addColumn('number', 'Value');
// ---<
for (var i = 0; i < msg.valueArr.length; i++) {
data.addRow([msg.timeArr[i], msg.valueArr[i]]);
}
chart.draw(data, options);
}
function parseData(msg) {
//... declare timeArr & valueArr locally here
return {
timeArr: timeArr,
valueArr: valueArr
};
}
function startData() {
try {
socket = new WebSocket(portal);
//console.log('WebSocket status '+socket.readyState);
socket.onopen = function(msg) {
//console.log("Welcome - status "+this.readyState);
};
socket.onmessage = function(msg) {
if (getData) {
getData = false;
// pass object with arrays from parseData
drawVisualization(parseData(msg));
}
};
socket.onclose = function(msg) {
//console.log("Disconnected - status "+this.readyState);
};
}
catch(ex){
console.log(ex);
}
}
startData();
}
I have a requirement as below.
I need to input time series data (day data) using a graph. The data is usually like below but the profile can be changed depending upon the situation.
Right now the data is being manually entered in textboxes which makes it very difficult.
I am wondering whether there are solutions that let user draw on a chart and generate the data in the back. In other words, the user picks certain points and the profile is drawn.
see following working snippet, click on the chart to add a data point...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
"cols": [
{"label": "x", "type": "number"},
{"label": "y", "type": "number"}
]
});
var axisMax = 10;
var ticks = [];
for (var i = 0; i <= axisMax; i = i + 0.5) {
ticks.push(i);
}
var options = {
chartArea: {
bottom: 64,
height: '100%',
left: 64,
top: 24,
width: '100%'
},
hAxis: {
format: '0.0',
textStyle: {
fontSize: 9
},
ticks: ticks,
title: data.getColumnLabel(0),
viewWindow: {
min: 0,
max: axisMax
}
},
height: 600,
legend: {
position: 'top'
},
pointSize: 4,
vAxis: {
format: '0.0',
textStyle: {
fontSize: 9
},
ticks: ticks,
title: data.getColumnLabel(1),
viewWindow: {
min: 0,
max: axisMax
}
}
};
var tableDiv = document.getElementById('table_div');
var table = new google.visualization.Table(tableDiv);
var chartDiv = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(chartDiv);
var chartLayout = null;
google.visualization.events.addListener(chart, 'ready', function () {
chartLayout = chart.getChartLayoutInterface();
});
google.visualization.events.addListener(chart, 'click', function (sender) {
data.addRow([
chartLayout.getHAxisValue(sender.x),
chartLayout.getVAxisValue(sender.y)
]);
drawChart();
});
function drawChart() {
chart.draw(data, options);
table.draw(data);
}
window.addEventListener('resize', drawChart, false);
drawChart();
},
packages:['corechart', 'table']
});
div {
text-align: center;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="table_div"></div>
I am working on a small class to handle Google Chart and for some odd reason I keep getting
googleChart.js:86 Uncaught TypeError: this.swapChart is not a function
On the page I have a button with id "btnSwitch", click on which triggers a switch of the chart from chart view to the table view and vice-versa. This is defined within this.addChartSwitchListener() and called within this.init_chart()
I can call this.swapChart() within init method so I have to assume that issue is with:
_button.addEventListener('click', this.switchChart, false);
Here is my code below:
google.load('visualization', '1.0', {'packages': ['charteditor', 'controls']});
//google.setOnLoadCallback(drawDashboard);
var GChart = GChart || (function () {
var _graphType;
var _minTime;
var _maxTime;
var _hAxisTitle;
var _vAxisTitle;
var _tableData;
var _data;
var _dashboard;
var _lineChart;
var _button;
var _showChart;
return {
init: function (tableData, graphType, minTime, maxTime, hAxisTitle, vAxisTitle) {
// google charts
//_google = google;
_tableData = tableData;
// load chart params
_graphType = graphType;
_minTime = minTime;
_maxTime = maxTime;
_hAxisTitle = hAxisTitle;
_vAxisTitle = vAxisTitle;
// some other initialising
this.build_googlechart();
},
build_googlechart: function ()
{
this.init_chart();
// also tried this - with the same result.
// google.load('visualization', '1.0', {'packages':['corechart'], 'callback': this.drawChart});
},
init_chart: function ()
{
// var data = new google.visualization.DataTable();
_data = new google.visualization.DataTable(_tableData);
// Create a dashboard.
_dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
if (_graphType === 'LineChart') {
this.lineChart();
} else {
this.columnChart();
}
this.addChartSwitchListener();
},
addChartSwitchListener: function ()
{
_button = document.getElementById('btnSwitch');
_button.addEventListener('click', this.switchChart, false);
_showChart = "Chart";
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(_lineChart, 'ready', function () {
if (_showChart !== 'Table') {
$('.save_chart').show();
$('.save_chart').removeClass('disabled');
$('.save_chart').attr('href', _lineChart.getChart().getImageURI());
$('#filter_div').show();
} else {
$('.save_chart').hide();
$('#filter_div').hide();
}
});
},
swapChart: function ()
{
var chart = "Table";
if (_showChart === "Chart") {
chart = _graphType;
}
_lineChart.setChartType(chart);
_lineChart.setOptions(this.getOptions(_showChart));
_lineChart.draw();
},
switchChart: function ()
{
_showChart = _button.value;
this.swapChart();
_showChart = (_showChart === 'Table') ? 'Chart' : 'Table';
_button.value = _showChart;
},
getOptions: function (chartType)
{
var options;
switch (chartType) {
case 'Chart':
options = {
backgroundColor: {
fill: 'transparent'
},
legend: 'right',
pointSize: 5,
crosshair: {
trigger: 'both'
},
hAxis: {
},
vAxis: {
}
};
break;
case 'Table':
options = {
showRowNumber: true,
width: '100%',
height: '100%'
};
break;
default:
options = {};
}
return options;
},
lineChart: function ()
{
var lineChartRangeFilter = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'filter_div',
'options': {
filterColumnIndex: 0,
ui: {
chartType: 'LineChart',
chartOptions: {
backgroundColor: {fill: 'transparent'},
height: '50',
chartArea: {
width: '90%'
}
}
}
}
});
// Create a pie chart, passing some options
_lineChart = new google.visualization.ChartWrapper({
'chartType': "LineChart",
'containerId': 'chart_div',
'options': {
backgroundColor: {fill: 'transparent'},
'legend': 'right',
'pointSize': 5,
crosshair: {trigger: 'both'}, // Display crosshairs on focus and selection.
hAxis: {
title: _hAxisTitle,
viewWindow: {
min: _minTime,
max: _maxTime
},
},
vAxis: {
title: _vAxisTitle
}
}
});
// Establish dependencies, declaring that 'filter' drives 'pieChart',
// so that the pie chart will only display entries that are let through
// given the chosen slider range.
_dashboard.bind(lineChartRangeFilter, _lineChart);
// Draw the dashboard.
_dashboard.draw(_data);
},
columnChart: function () {
_lineChart = new google.visualization.ChartWrapper({
'chartType': "ColumnChart",
'containerId': 'chart_div',
'dataTable': _data,
'options': {backgroundColor: {fill: 'transparent'},
'legend': 'right',
'pointSize': 5,
crosshair: {trigger: 'both'}, // Display crosshairs on focus and selection.
hAxis: {
title: _hAxisTitle,
},
vAxis: {
title: _vAxisTitle,
}
}
});
_lineChart.draw();
}
};
}());
This is because you pass a reference to that method to addEventListener, which will later be called with the window object as context, and not your this object.
To overrule this behaviour, you can use several solutions, but here is one with bind():
_button.addEventListener('click', this.switchChart.bind(this), false);
I have two charts, they are being created by javascript the same exact way, one of them shows the values on x axis properly, the other doesn't.
So this is the traffic chart
As you can see the dates are shown properly under x axis, here is the code that generates this chart
function drawTrafficChart(processedData, humanReadableName, params) {
dataArray = [];
dataArrayRow = ['Date', 'Impressions', 'Detail Page Views'];
dataArray.push(dataArrayRow);
for (i in processedData) {
dateString = processedData[i].date;
dateString = formatDateStringAccordingToAggregationType(dateString, params);
dataArrayRow = [dateString, processedData[i].event1, processedData[i].event2];
dataArray.push(dataArrayRow);
}
var dataTable = google.visualization.arrayToDataTable(dataArray);
var chartOptions = {
title: 'Traffic Chart',
hAxis: {title: humanReadableName},
vAxis: {minValuex: 0},
pointSize: 5,
width: 670,
height: 300
};
var chart = new google.visualization.LineChart(document.getElementById('traffic_chart'));
chart.draw(dataTable, chartOptions);
}
And this is the click chart
Here is the code that generates click chart
function drawClickChart(processedData, humanReadableName, params) {
dataArray = [];
dataArrayRow = ['Date', 'Website Clicks', 'Image Clicks', 'Video Clicks'];
dataArray.push(dataArrayRow);
for (i in processedData) {
dateString = processedData[i].date;
dateString = formatDateStringAccordingToAggregationType(dateString, params);
dataArrayRow = [dateString, processedData[i].event3, processedData[i].event4, processedData[i].event5];
dataArray.push(dataArrayRow);
}
var dataTable = google.visualization.arrayToDataTable(dataArray);
var chartOptions = {
title: 'Click Chart',
hAxis: {title: humanReadableName},
vAxis: {minValuex: 0},
pointSize: 5,
width: 670,
height: 300
};
var chart = new google.visualization.LineChart(document.getElementById('click_chart'));
chart.draw(dataTable, chartOptions);
}
As you can see the dates on x axis are messed up, is there something I could do to fix this?