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...
To change the point size, I set pointsize to 10 (for example).
options: {
pointSize: 10,
}
I would like to add a border to this point. Any idea ?
using a data view, you can apply a style to all the rows using a column role...
here, the view will include columns 0, 1 from the data,
and add a third calculated column for the style...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return 'point {stroke-color: #F00; stroke-width: 2;}';
},
role: 'style',
type: 'string'
}]);
then you must use the view when drawing the dashboard...
dashboard.draw(view);
see following working snippet...
google.charts.load('current', {packages: ['corechart', 'controls'],'language': 'fr'});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1AOVg0jYaDvoHQeXBcDtJ6HdkBkkcQhEBi9Xo_crOvlk/edit?usp=sharing');
query.send(drawDashboard);
}
function drawDashboard(response) {
var data = response.getDataTable();
var chart = new google.visualization.ChartWrapper({
chartType: 'AreaChart',
containerId: 'chart_div',
options: {
// width and chartArea.width should be the same for the filter and chart
height: 400,
colors: ['#4aadde'],
curveType: 'function',
pointSize: 5,
chartArea: {
width: '75%'
},
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'},format: 'd MMM yyyy' },
vAxis: {minValue: 0}
}
});
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
return 'point {stroke-color: #F00; stroke-width: 2;}';
},
role: 'style',
type: 'string'
}]);
var control = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'control_div',
options: {
filterColumnIndex: 0,
ui: {
'chartType': 'AreaChart',
chartOptions: {
height: 50,
areaOpacity: 0.9,
colors: ['#5dade0'],
chartArea: {
width: '75%'
}
},
minRangeSize: 86400000, // 86400000ms = 1 day
snapToData: true
}
},
state: {
range: {
// set the starting range to January 2012
start: new Date(2017, 05, 15),
}
}
});
var dashboard = new google.visualization.Dashboard(document.querySelector('#dashboard_div'));
dashboard.bind([control], [chart]);
dashboard.draw(view);
function zoomLastDay () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 1),
end: range.max
}
});
control.draw();
}
function zoomLastWeek () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 7),
end: range.max
}
});
control.draw();
}
function zoomLastMonth () {
// zoom here sets the month back 1, which can have odd effects when the last month has more days than the previous month
// eg: if the last day is March 31, then zooming last month will give a range of March 3 - March 31, as this sets the start date to February 31, which doesn't exist
// you can tweak this to make it function differently if you want
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth() - 1, range.max.getDate()),
end: range.max
}
});
control.draw();
}
var runOnce = google.visualization.events.addListener(dashboard, 'ready', function () {
google.visualization.events.removeListener(runOnce);
if (document.addEventListener) {
document.querySelector('#lastDay').addEventListener('click', zoomLastDay);
document.querySelector('#lastWeek').addEventListener('click', zoomLastWeek);
document.querySelector('#lastMonth').addEventListener('click', zoomLastMonth);
}
else if (document.attachEvent) {
document.querySelector('#lastDay').attachEvent('onclick', zoomLastDay);
document.querySelector('#lastWeek').attachEvent('onclick', zoomLastWeek);
document.querySelector('#lastMonth').attachEvent('onclick', zoomLastMonth);
}
else {
document.querySelector('#lastDay').onclick = zoomLastDay;
document.querySelector('#lastWeek').onclick = zoomLastWeek;
document.querySelector('#lastMonth').onclick = zoomLastMonth;
}
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<input id="lastDay" type="button" value="Hier" />
<input id="lastWeek" type="button" value="Dernière semaine" />
<input id="lastMonth" type="button" value="Dernier mois" />
<div id="chart_div"></div>
<div id="control_div"></div>
</div>
note: the following line (last in the fiddle) is for the old jsapi library
it isn't needed and should be removed...
google.load('visualization', '1', {packages:['controls'], callback: drawChart});
My JSON array, which I'm getting by ajax response, looks like that:
[["\u041f\u0435\u0440\u0438\u043e\u0434","\u041a\u043b\u0438\u0435\u043d\u0442\u044b","\u0421\u0434\u0435\u043b\u043a\u0438","\u0421\u0443\u043c\u043c\u0430 \u0441\u0434\u0435\u043b\u043e\u043a","\u041e\u043f\u043b\u0430\u0447\u0435\u043d\u043d\u044b\u0435 \u0441\u0434\u0435\u043b\u043a\u0438"],["2017-02-18",0,0,0,0],["2017-02-19",1,0,0,0],["2017-02-20",2,0,0,0],["2017-02-21",4,1,64000,0],["2017-02-22",0,0,0,0],["2017-02-23",3,0,0,0],["2017-02-24",1,0,0,0],["2017-02-25",0,0,0,0],["2017-02-26",2,0,0,0],["2017-02-27",1,1,50000,0],["2017-02-28",1,0,0,0]...etc
So, everythings works fine, my X-axis labels looks good, but I can't understand how can I:
1) make them in date format for Google Chart understand that this is date and
2) group them by month by clicking some button
All problems come from my way of Google Charts implementing.
Here's the code.
function drawChart() {
var obj ='[["\u041f\u0435\u0440\u0438\u043e\u0434","\u041a\u043b\u0438\u0435\u043d\u0442\u044b","\u0421\u0434\u0435\u043b\u043a\u0438","\u0421\u0443\u043c\u043c\u0430 \u0441\u0434\u0435\u043b\u043e\u043a","\u041e\u043f\u043b\u0430\u0447\u0435\u043d\u043d\u044b\u0435 \u0441\u0434\u0435\u043b\u043a\u0438"],["2017-02-18",0,0,0,0],["2017-02-19",1,0,0,0],["2017-02-20",2,0,0,0],["2017-02-21",4,1,64000,0],["2017-02-22",0,0,0,0],["2017-02-23",3,0,0,0],["2017-02-24",1,0,0,0],["2017-02-25",0,0,0,0],["2017-02-26",2,0,0,0],["2017-02-27",1,1,50000,0],["2017-02-28",1,0,0,0],["2017-03-01",0,0,0,0],["2017-03-02",6,0,0,0],["2017-03-03",2,0,0,0],["2017-03-04",1,0,0,0],["2017-03-05",1,0,0,0],["2017-03-06",10,0,0,0],["2017-03-07",1,0,0,0],["2017-03-08",1,0,0,0],["2017-03-09",0,0,0,0],["2017-03-10",9,0,0,0],["2017-03-11",0,0,0,0],["2017-03-12",3,0,0,0],["2017-03-13",3,0,0,0],["2017-03-14",1,0,0,0],["2017-03-15",6,0,0,0],["2017-03-16",1,0,0,0],["2017-03-17",1,0,0,0],["2017-03-18",0,0,0,0],["2017-03-19",5,0,0,0],["2017-03-20",5,0,0,0]]';
data = google.visualization.arrayToDataTable($.parseJSON(obj));
var options = {
crosshair: {
trigger: 'both',
orientation: 'vertical'
},
focusTarget: 'category',
chartArea:{left:40,top:40,width:"85%"},
hAxis: {
format: 'MM'
},
vAxes: {
0: {},
1: {title: 'Cумма'},
},
series: {0: {targetAxisIndex:0},
1:{targetAxisIndex:0},
2:{targetAxisIndex:1},
3:{targetAxisIndex:1},
},
animation:{
duration: 750,
// easing: 'out',
startup: true
},
backgroundColor: 'aliceblue'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div')
);
chart.draw(data, options);
}
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://www.google.com/jsapi?ext.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 100%; height: 400px;"></div>
1) for google to recognize the first column as a date, need to use the following format in the json...
"Date(year, month, day, hours, minutes, days, seconds, milliseconds)"
e.g.
["Date(2017, 1, 18)",0,0,0,0],["Date(2017, 1, 19)",1,0,0,0],
month is zero-based --> 1 = Feb
or, you can use a view and a calculated column to convert, see snippet...
2) use the group() method to group by month
see following working snippet...
function drawChart() {
var obj ='[["\u041f\u0435\u0440\u0438\u043e\u0434","\u041a\u043b\u0438\u0435\u043d\u0442\u044b","\u0421\u0434\u0435\u043b\u043a\u0438","\u0421\u0443\u043c\u043c\u0430 \u0441\u0434\u0435\u043b\u043e\u043a","\u041e\u043f\u043b\u0430\u0447\u0435\u043d\u043d\u044b\u0435 \u0441\u0434\u0435\u043b\u043a\u0438"],["2017-02-18",0,0,0,0],["2017-02-19",1,0,0,0],["2017-02-20",2,0,0,0],["2017-02-21",4,1,64000,0],["2017-02-22",0,0,0,0],["2017-02-23",3,0,0,0],["2017-02-24",1,0,0,0],["2017-02-25",0,0,0,0],["2017-02-26",2,0,0,0],["2017-02-27",1,1,50000,0],["2017-02-28",1,0,0,0],["2017-03-01",0,0,0,0],["2017-03-02",6,0,0,0],["2017-03-03",2,0,0,0],["2017-03-04",1,0,0,0],["2017-03-05",1,0,0,0],["2017-03-06",10,0,0,0],["2017-03-07",1,0,0,0],["2017-03-08",1,0,0,0],["2017-03-09",0,0,0,0],["2017-03-10",9,0,0,0],["2017-03-11",0,0,0,0],["2017-03-12",3,0,0,0],["2017-03-13",3,0,0,0],["2017-03-14",1,0,0,0],["2017-03-15",6,0,0,0],["2017-03-16",1,0,0,0],["2017-03-17",1,0,0,0],["2017-03-18",0,0,0,0],["2017-03-19",5,0,0,0],["2017-03-20",5,0,0,0]]';
var data = google.visualization.arrayToDataTable($.parseJSON(obj));
// create date formatter
var formatDate = new google.visualization.DateFormat({
pattern: 'MM'
});
// create view with calculated column
var view = new google.visualization.DataView(data);
view.setColumns([
// col 0 - x
{
label: 'date',
type: 'date',
calc: function (dt, row) {
return new Date(dt.getValue(row, 0))
}
},
// col 1 - y
1
]);
// group by month
var groupData = google.visualization.data.group(
// data table
view,
// group by fields
[{column: 0, type: 'string', modifier: function (xValue) {
return formatDate.formatValue(new Date(xValue));
}}],
// aggregate fields
[
{
aggregation: google.visualization.data.sum,
column: 1,
label: 'Total',
type: 'number'
}
]
);
var options = {
crosshair: {
trigger: 'both',
orientation: 'vertical'
},
focusTarget: 'category',
chartArea:{left:40,top:40,width:"85%"},
hAxis: {
format: 'MM'
},
vAxes: {
0: {},
1: {title: 'C????'},
},
series: {0: {targetAxisIndex:0},
1:{targetAxisIndex:0},
2:{targetAxisIndex:1},
3:{targetAxisIndex:1},
},
animation:{
duration: 750,
easing: 'inAndOut',
startup: true
},
backgroundColor: 'aliceblue'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div')
);
// draw grouped data
chart.draw(groupData, options);
}
google.charts.load('current', {
callback: function () {
drawChart();
window.addEventListener('resize', drawChart, false);
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="chart_div"></div>
I have been having trouble trying to set up a Google Charts dashboard with two charts and two controlwrappers using two queries to a Google sheet.
I have gone through many of the examples on here demonstrating multiple graphs from single sources, or multiple queries for multiple charts but no control aspect.
I am ultimately trying to run two queries of a single Google sheet, each query pulling a different set of data from the sheet based on the query string, then displaying the data in a graph. There would also be a filterColumn control wrapper that selects data from the data table.
I have the following code which works for one query and graph. When I try to double up the process so that I can display both in one page, one or the other graph will appear, but not both.
I get that this may be something to do with a conflict between the queries, but I don't understand it.
I tried building one function that ran both queries that would be initiated by the google.setOnLoadCallback function. However, that didn't work. I tried to combine the various parts using others examples as guides, but those don't work.
This is the closest version, and when I refresh it several times in a row sometimes one chart will load, other times the other, but never both.
If someone can point me in the right direction I would appreciate it.
<html>
<head>
<title>Google visualisation demo: chart query controls</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the controls package.
// Packages for all the other charts you need will be loaded
// automatically by the system.
google.load('visualization', '1.1', {
'packages': ['controls', 'linechart', 'corechart']
});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initialize);
google.setOnLoadCallback(initialize2);
function initialize() {
var queryString = encodeURIComponent("select B, ((5-avg(F))*.4) + ((5-avg(G))*.4) + ((5-avg(H))*.2) + ((5-avg(I))*.125) + ((5-avg(J))*.125) where C contains 'Sept 26' and E contains 'Forced' group by B");
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1_DuiDpbRyegaN0zYR4iYp8ZXefO-kIV-F054e9aIcIY/gviz/tq?gid=1757506986&headers=1&tq=' + queryString);
// Send the query with a callback function.
query.send(drawDashboard);
}
function initialize2() {
var queryString2 = encodeURIComponent("select B, ((5-avg(F))*.4) + ((5-avg(G))*.4) + ((5-avg(H))*.2) + ((5-avg(I))*.125) + ((5-avg(J))*.125) where C contains 'Sept 26' and E contains 'Unforced' group by B");
var query2 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1_DuiDpbRyegaN0zYR4iYp8ZXefO-kIV-F054e9aIcIY/gviz/tq?gid=1757506986&headers=1&tq=' + queryString2);
// Send the query with a callback function.
query2.send(drawDashboard2);
}
function drawDashboard(response) {
var data = response.getDataTable();
// Everything is loaded. Assemble your dashboard...
var namePicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Sample ID',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var laptimeChart = new google.visualization.ChartWrapper({
'chartType': 'Bar',
'containerId': 'chart_div',
'dataSourceUrl': 'https://docs.google.com/spreadsheets/d/1_DuiDpbRyegaN0zYR4iYp8ZXefO-kIV-F054e9aIcIY/gviz/tq?gid=1757506986&headers=1',
'query': "select B, ((5-avg(F))*.4) + ((5-avg(G))*.4) + ((5-avg(H))*.2) + ((5-avg(I))*.125) + ((5-avg(J))*.125) where C contains 'Sept 26' and E contains 'Forced' group by B",
'options': {
'width': 1600,
'height': 800,
axes: {
x: {
0: {
side: 'top',
label: 'Sample ID'
} // Top x-axis.
}
},
chart: {
title: 'Aging Panel Results',
subtitle: 'Beer force-aged for 2 weeks',
},
'legend': {
position: 'none'
},
'colors': ['#ed8907']
}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div')).
bind(namePicker, laptimeChart).
draw(data)
}
function drawDashboard2(response2) {
var data2 = response2.getDataTable();
// Everything is loaded. Assemble your dashboard...
var namePicker2 = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'filter_div2',
'options': {
'filterColumnLabel': 'Sample ID',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
var laptimeChart2 = new google.visualization.ChartWrapper({
'chartType': 'Bar',
'containerId': 'chart_div2',
'options': {
'width': 1600,
'height': 800,
axes: {
x: {
0: {
side: 'top',
label: 'Sample ID'
} // Top x-axis.
}
},
chart: {
title: 'Aging Panel Results',
subtitle: 'Beer aged 2 weeks',
},
'legend': {
position: 'none'
},
'colors': ['Red']
}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div2')).
bind(namePicker2, laptimeChart2).
draw(data2)
}
</script>
</head>
<body>
<!--Div that will hold the dashboard-->
<div id="dashboard_div">
<!--Divs that will hold each control and chart-->
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>
<div id="dashboard_div2">
<!--Divs that will hold each control and chart-->
<div id="filter_div2"></div>
<div id="chart_div2"></div>
</div>
</body>
</html>
first, need to use loader.js for loading the libraries,
this...
<script src="https://www.gstatic.com/charts/loader.js"></script>
not this...
<script src="https://www.google.com/jsapi"></script>
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
second, you should only use google.setOnLoadCallback once per page
it can also be included in the google.charts.load statement, as in the following example
next, the chartType is incorrect and needs to exist in the packages loaded
for core charts, load package 'corechart' and use --> chartType: 'BarChart'
for material charts, load package: 'bar' --> chartType: 'Bar'
(don't recommend using material charts, several options don't work)
finally, since the chart wrappers are drawn using a dashboard,
don't need these options --> 'dataSourceUrl' or 'query'
see following working snippet...
google.charts.load('current', {
callback: function () {
var queryString = encodeURIComponent("select B, ((5-avg(F))*.4) + ((5-avg(G))*.4) + ((5-avg(H))*.2) + ((5-avg(I))*.125) + ((5-avg(J))*.125) where C contains 'Sept 26' and E contains 'Forced' group by B");
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1_DuiDpbRyegaN0zYR4iYp8ZXefO-kIV-F054e9aIcIY/gviz/tq?gid=1757506986&headers=1&tq=' + queryString);
query.send(drawDashboard);
var queryString2 = encodeURIComponent("select B, ((5-avg(F))*.4) + ((5-avg(G))*.4) + ((5-avg(H))*.2) + ((5-avg(I))*.125) + ((5-avg(J))*.125) where C contains 'Sept 26' and E contains 'Unforced' group by B");
var query2 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1_DuiDpbRyegaN0zYR4iYp8ZXefO-kIV-F054e9aIcIY/gviz/tq?gid=1757506986&headers=1&tq=' + queryString2);
query2.send(drawDashboard2);
},
packages: ['controls', 'corechart']
});
function drawDashboard(response) {
var namePicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'filter_div',
options: {
filterColumnLabel: 'Sample ID',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: false
}
}
});
var laptimeChart = new google.visualization.ChartWrapper({
chartType: 'BarChart',
containerId: 'chart_div',
options: {
width: 1600,
height: 800,
axes: {
x: {
0: {
side: 'top',
label: 'Sample ID'
}
}
},
chart: {
title: 'Aging Panel Results',
subtitle: 'Beer force-aged for 2 weeks',
},
legend: {
position: 'none'
},
colors: ['#ed8907']
}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div')).
bind(namePicker, laptimeChart).
draw(response.getDataTable());
}
function drawDashboard2(response) {
var namePicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'filter_div2',
options: {
filterColumnLabel: 'Sample ID',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: false
}
}
});
var laptimeChart = new google.visualization.ChartWrapper({
chartType: 'BarChart',
containerId: 'chart_div2',
options: {
width: 1600,
height: 800,
axes: {
x: {
0: {
side: 'top',
label: 'Sample ID'
}
}
},
chart: {
title: 'Aging Panel Results',
subtitle: 'Beer force-aged for 2 weeks',
},
legend: {
position: 'none'
},
colors: ['#ed8907']
}
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div2')).
bind(namePicker, laptimeChart).
draw(response.getDataTable());
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="dashboard_div">
<div id="filter_div"></div>
<div id="chart_div"></div>
</div>
<div id="dashboard_div2">
<div id="filter_div2"></div>
<div id="chart_div2"></div>
</div>
How exactly do I use the jquery ui slider instead of a numberrange filter. I have an idea of how each work, but am unsure how this needs to be related to the chart data.
EDIT: Whole code(sorry about comments):
<!DOCTYPE html>
<head>
<title>Google Chart Example</title>
<script src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<!-- <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> -->
<script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<!--script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script-->
<!--script src="http://code.jquery.com/jquery-1.10.2.js"></script-->
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['controls']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Prepare the data
//$.get("abc.csv - abc.csv.csv", function(csvString) {
$.get("Data_Actual_V2.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// use arrayData to load the select elements with the appropriate options
for (var i = 1; i < arrayData[0].length; i++) { // i starts from 1, not 0 because the first column is text
// this adds the given option to both select elements
$("select").append("<option value='" + i + "'>" + arrayData[0][i] + "</option");
}
// set the default selection
$("#range option[value='1']").attr("selected","selected");
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var columnsTable = new google.visualization.DataTable();
columnsTable.addColumn('number', 'colIndex');
columnsTable.addColumn('string', 'colLabel');
var initState = {
selectedValues: []
};
// put the columns into this data table (skip column 0)
for (var i = 2; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
}
initState.selectedValues.push(data.getColumnLabel(4));
var CountryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'control3',
options: {
filterColumnLabel: 'Location',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true,
caption: 'Country',
label: 'Country'
}
}
});
/*var slider2 = new google.visualization.ControlWrapper({
//'controlType': 'DateRangeFilter',
'controlType': 'NumberRangeFilter',
'containerId': 'control4',
'options': {
//'ui.format': 'pattern:"yyyy"',
// 'ui.format': 'fractionDigits: 0',
'filterColumnLabel': 'Year',
'ui': { 'format': { 'fractionDigits':'0',
'groupingSymbol':'' } }
},
}); */
//Define a chart to show AML CFT Risk per country
var options1 = {
title: 'A',
displayMode: 'regions',
//width: 1000,
datalessRegionColor: 'C0C0C0',
hAxis: {title: 'Year', }
colorAxis: {
values: [0, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100],
colors: ['#3366FF','#33CCCC', '#00FFFF', '#CCFFFF', '#00FF00', '#FFFF99','#FFCC00','#FF9900','#FF0000'],
minValue: 0,
maxValue: 100,
}
}
var xA;
//var yB = 4;
/*var view1 = { // Defines data to show in geoChart
columns: [x1, y1] //[0,4]
}*/
var geoChart = new google.visualization.ChartWrapper({
chartType: 'GeoChart',
containerId: 'chart1',
options: options1,
view: {
columns: [0, 4]
}
});
$(function() {
$('#slider').slider({
disabled: true,
range: 'min',
value: 44,
min: 1969,
max: 2013,
change: function(event, ui) {
$('#header').text('debug=' + ui.value);
//options1.minValue = ui.value;/////HERE TO LINK TO ABOVE
xA = ui.value;
console.log(xA);
//drawChart();
setChartView();
}
});
});
var GenderPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'control2',
dataTable: columnsTable,
options: {
filterColumnLabel: 'colLabel',
ui: {
label: 'Columns',
allowTyping: false,
allowMultiple: false,
allowNone: false,
selectedValuesLayout: 'belowStacked'
}
},
state: initState
});
function setChartView() {
var state = GenderPicker.getState();
var row;
var view = {
columns: [0]
};
for (var i = 0; i < state.selectedValues.length; i++) {
row = columnsTable.getFilteredRows([{
column: 1,
value: state.selectedValues[i]
}])[0];
view.columns.push(columnsTable.getValue(row, 0));
}
// sort the indices into their original order
view.columns.sort(function (a, b) {
return (a - b);
});
geoChart.setView(view);
geoChart.draw();
}
google.visualization.events.addListener(GenderPicker, 'statechange', setChartView);
google.visualization.events.addOneTimeListener(geoChart, 'ready', function () {
$('#slider').slider('enable');
setChartView();
});
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
dashboard.bind([CountryPicker/*, slider2*/],[geoChart]). // consolidated all of the bind calls
// Draw the dashboard
draw(data);
GenderPicker.draw();
});
}
<body>
<div id="dashboard">
<table>
<tr style='vertical-align: top'>
<td style='width: 300px; font-size: 0.9em;'>
<div id="control1"></div>
<div id="control2"></div>
<div id="control3"></div>
<div id="control4"></div>
<div id="slider"></div>
<h3 id ="header">Sometext</h3>
</td>
<td style='width: 600px'>
<div style="float: left;" id="chart1"></div>
</td>
</tr>
</table>
</div>
</body>
</html>
Have been trying to follow: Using jQuery slider to change Google chart viewWindow
With a bit of this as well: https://stackoverflow.com/questions/26154248/how-to-display-various-controlwrappers-from-2-datatables-with-a-single-geochart?noredirect=1#comment41031194_26154248
EDIT V2
I solved it by using the standard google slider, and assigning my jquery slider value to it's 'highValue'. I then set the div containing the google slider to display: none.
var slider2 = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'control4',
'options': {
'filterColumnLabel': 'Year',
'ui': { 'format': { 'fractionDigits':'0',
'groupingSymbol':'' } }
},
});
$(function() {
$('#slider').slider({
disabled: true,
range: 'min',
value: 53,
min: 1960,
max: 2013,
change: function(event, ui) {
$('#header').text('debug=' + ui.value);
//options1.minValue = ui.value;/////HERE TO LINK TO ABOVE
xA = ui.value;
console.log(xA);
//drawChart();
slider2.setState({'highValue': ui.value});
slider2.draw();
setChartView();
}
});
});
<div id="control4" style="display: none;"></div>
Definitely, not the nicest or most correct method of doing this, however it did solve the problem.