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'm wondering how I could limit the MAX amount of items it can display to my chart to 5. I've got a cron job updating the .json daily, and currently it just tries to fit them all onto there.
This is my code:
<script>
google.charts.load("visualization", "1", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/server/database.json",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Players Hourly',
'is3D':true,
legend: 'bottom',
hAxis: {
minValue: 0,
format: 'long'
},
vAxis: {
minValue: 0,
scaleType: 'log',
format: 'long'
},
pointSize: 5,
series: {
0: { pointShape: 'circle' },
}
};
var chart = new google.visualization.LineChart(document.getElementById('serverstats'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>
Thank you.
an easy way would be to use a data view and the setRows method.
then use the view to draw the chart.
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setRows([0, 1, 2, 3, 4]); //<-- provide an array of the row indexes you want to see
...
chart.draw(view, options); //<-- use view here
EDIT
to show the last 5 rows...
var viewRows = [];
for (var i = data.getNumberOfRows() - 1; i > data.getNumberOfRows() - 6; i--) {
viewRows.push(i);
}
view.setRows(viewRows);
I want to create a google diff chart for a survey. that will show the total number of user and survey given users.
My javascript code is:-
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var overallData = [];
var givenData = [];
overallData.push(['Department', 'Total Users']);
givenData.push(['Department', 'Given feedback']);
for (var i in data) {
overallData.push([data[i].department_name, data[i].emp_count]);
givenData.push([data[i].department_name, data[i].upward_done]);
}
var oldData = google.visualization.arrayToDataTable(overallData);
var newData = google.visualization.arrayToDataTable(givenData);
var colChartDiff = new google.visualization.ColumnChart(document.getElementById('feedback_dept_chart'));
var options = {
fontName: 'Calibri',
legend: 'none',
height: 200,
width: 960,
vAxis: {title: 'No of employee'},
tooltip: {isHtml: false}
};
var diffData = colChartDiff.computeDiff(oldData, newData);
colChartDiff.draw(diffData, options);
And data is :-
[{"department_name":"Design","emp_count":1,"upward_done":1},
{"department_name":"Management","emp_count":1,"upward_done":0},
{"department_name":"Technology","emp_count":3,"upward_done":2}]
The problem with diff chart is it is showing tooltip named "current" and "previous". And I want to change it by "total users" and "survey given users".
Any help will be appreciated.
Thanks
Add below code for tooltip into options
diff: {
oldData: { opacity: 1, color: 'yellow',
tooltip:{
prefix:'Label 1'
}
},
newData: { opacity: 1, widthFactor: 1,
tooltip:{
prefix:'Label 2'
}
}
}
I have problem with using Google.charts api... i have chart drawing function like this:
function columnDraw(sectionname) {
var data = google.visualization.arrayToDataTable(array);
var view = new google.visualization.DataView(data);
var options = {
title: "Activity of users",
bar: {groupWidth: "100%"},
legend: {position: "top"},
height: 300,
// explorer: {
//maxZoomOut:0
//maxZoomIn: 50,
// keepInBounds: true,
// axis: 'horizontal'
// },
hAxis: {
title: 'Amount of activity',
minValue : 0,
format: '0'
},
vAxis: {
title: 'Amount of users',
minValue : 0,
format: '0'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById(sectionname));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
document.getElementById("input0").value = data.getValue(selectedItem.row, 0);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(view, options);
}
I want to choose parts of chartcolumn by cklicing on them, but i have a problem with zooming. This code works but once I uncomment the explorer part, selectHandler function wont work properly. Can anyone tell me whats wrong with it?
You're missing a ","
maxZoomOut:0,
I am making pie chart from high chart library. I want to change color of each slice in pie chart
How can i do this ? My code is -
var colors = ["color:'#2a8482'","color:'#64DECF'","color:'#BCCDF8'"];
var responseData = {"2":40,"1":30}
var obj = $.parseJSON(responseData);
var dataArrayFinal = Array();
var value = Array();
var name = Array();
var j = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
name[j] = "name:'"+key+"'";
value[j] = obj[key];
j++;
}
}
for(k=0;k<name.length;k++) {
var temp = new Array(name[k],value[k],colors[k]);
dataArrayFinal[k] = temp;
}
$(function () {
new Highcharts.Chart({
chart: {
renderTo: 'container'+counter,
type: 'pie',
height: 280,
width: 280
},
title: {
text: ' '
},
tooltip: {
valueSuffix: '%',
positioner: function () {
return {
x: this.chart.series[0].center[0] -
(this.label.width / 2) + 8,
y: this.chart.series[0].center[1] -
(this.label.height / 2) + 8
};
}
},
series: [{
name: 'Answer',
size: '100%',
innerSize: '65%',
data: dataArrayFinal
}]
});
});
In this graph is coming but colors are not changed. They are taking default color.
Highcharts.setOptions({
colors: ['#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
It should work that way ;-)
if you change your color-array to:
var colors = ["#2a8482","#64DECF","#BCCDF8"];
and then at the beginning of your function:
$(function () {
add the following code:
Highcharts.getOptions().plotOptions.pie.colors = colors;
this should do the trick.
Example of coloring can be found in this JSFiddle, created by the developers of HighCharts:
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/pie-monochrome/