I was playing around with trying to set the vertical axis scale in my google charts. I'm not happy with the auto scaling that it does since I have two results and want to see them on an even scale for apples-to-apples comparison.
This is my code. I have set the max and min values, yet that does not seem to apply in the output.
Code
function createExpenseChart(data) {
google.load("visualization", "1", {packages:["corechart"]});
var chartdata = new google.visualization.DataTable();
chartdata.addColumn('number', 'Expense');
chartdata.addColumn('number', '2013');
chartdata.addColumn('number', '2014');
for (var k in data["Expense"]["2013"]){
if (data["Expense"]["2013"].hasOwnProperty(k)) {
["2013"][k],10),parseInt(data["Expense"]["2014"][k],10)])
chartdata.addRow([parseInt(k,10),parseInt(data["Expense"]["2013"][k],10),parseInt(data["Expense"]["2014"][k],10)]);
}
}
var options = {'title':'2013 vs. 2014 comparison,
curveType: 'function',
viewWindowMode:'explicit',
viewWindow:{
max:100000,
min:10000
},
vAxis: {title: 'Cost ($)',
minValue: 0,
},
hAxis: {title: 'Expense (dollars)'},
height: 600,
width: 1000
};
var chart = new google.visualization.LineChart(document.getElementById('mydiv'));
chart.draw(chartdata, options);
}
I have also tried the following, but they don't show any effect
var options = {'title':'2013 v/s 2014',
curveType: 'function',
viewWindowMode:'explicit',
viewWindow:{
max:80,
min:20
},
vAxis: {
title: 'Cost ($)'
viewWindowMode:'explicit',
viewWindow: {
max:10000,
min:10000
}
},
hAxis: {title: 'Expense (dollars)'},
height: 600,
width: 1000
};
Sorry guys, this is resolved. Pretty much the same code worked me. I just had to clean my cache.
Sorry for the confusion.
function createExpenseChart(data) {
google.load("visualization", "1", {packExpenses:["corechart"]});
var chartdata = new google.visualization.DataTable();
chartdata.addColumn('number', 'Expense');
chartdata.addColumn('number', 'Previous Cost');
chartdata.addColumn('number', '2014 Cost');
for (var k in data["Expense"]["2013"]){
if (data["Expense"]["2013"].hasOwnProperty(k)) {
//console.log([parseInt(k,10),parseInt(data["Expense"]["2013"][k],10),parseInt(data["Expense"]["2014"][k],10)])
chartdata.addRow([parseInt(k,10),parseInt(data["Expense"]["2013"][k],10),parseInt(data["Expense"]["2014"][k],10)]);
}
}
var formatter = new google.visualization.NumberFormat({negativeColor: 'red', negativeParens: true, pattern: '$###,###'});
formatter.format(chartdata, 1);
formatter.format(chartdata, 2);
var options = {'title':'2013 vs. 2014 Costs by Expense',
curveType: 'function',
viewWindowMode:'explicit',
viewWindow:{
min:0
},
vAxis: {title: 'Cost ($)',
viewWindowMode : 'explicit',
viewWindow:
{
min: 0,
max:42000000
}
},
hAxis: {title: 'Expense (years)'},
height: 600,
width: 1000
};
var chart = new google.visualization.LineChart(document.getElementById('Expensecostdiv'));
chart.draw(chartdata, options);
}
Related
I have a Google Chart (column-chart) showing a single dated (Jan-2010 = 2010-01-01) column - but the resulting column seems to run from 1-Jul-09 through to 1-Jul-10 (note this seems to change depending on the width of the screen); how can I fix this so that the column sits only on the 01-Jan-2010 date? (**Note, the dates/values are variable and can include one or hundreds of column values so we CANNOT simply hard code this or change the column type from 'date' to 'string').
var arr = eval("[[new Date(2010, 0, 1), 0,1]]");
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dt');
data.addColumn('number', 'Open');
data.addColumn('number', 'Closed');
data.addRows(arr);
var options_stacked = {
isStacked: true,
height: 300,
colors: ['#111', '#a00'],
hAxis: {
slantedText: false,
format: 'd/MMM/yy',
},
legend: {
position: 'top',
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options_stacked);
A demonstrator for this can be found on https://jsfiddle.net/Abeeee/d5fojtp2/34/
you can add custom ticks to ensure each column "sits" on the correct date.
the ticks option expects an array of values.
we can use DataTable method --> getDistinctValue(colIndex)
to return the date values from the data table.
var xTicks = data.getDistinctValues(0);
hAxis: {
slantedText: false,
format: 'd.MMM.yy', <---- changed from 'd/MMM/yy' to avoid line breaks
ticks: xTicks
},
see following working snippet...
function doTest() {
var arr = eval("[[new Date(2010, 0, 1), 0,1]]");
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dt');
data.addColumn('number', 'Open');
data.addColumn('number', 'Closed');
data.addRows(arr);
var xTicks = data.getDistinctValues(0);
var options_stacked = {
isStacked: true,
height: 300,
colors: ['#111', '#a00'],
hAxis: {
slantedText: false,
format: 'd/MMM/yy',
ticks: xTicks
},
legend: {
position: 'top',
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options_stacked);
}
window.addEventListener('resize', doTest);
google.charts.load('current', {
packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(doTest);
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<h1>Google Charts</h1>
<div id="chart_div"></div>
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 try to custom vertical axis max and min value in google chart but nothing change.
I follow references from https://developers.google.com/chart/interactive/docs/gallery/combochart
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', '実績(件数)');
data.addColumn('number', '体調');
data.addRows([['03/19',2,5],['03/20',3,4],['03/21',3,3]]);
var materialOptions = {
seriesType: 'bars',
interpolateNulls: true,
series: {
0: {axis: '実績(件数)'},
1: {axis: '体調', targetAxisIndex:1, type:'line'}
},
height: 400,
vAxis: {
0: {
minValue: 0,
maxValue: 5.5
},
1: {
minValue: 1,
maxValue: 6
}
}
};
var materialChart = new google.visualization.ComboChart(chartDiv);
materialChart.draw(data, materialOptions);
I add isStacked: true like bellow
vAxis: { minValue: 0, maxValue: 5.5 }
isStacked: true,
See the example code:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Mac');
data.addColumn('number', 'Score');
data.addColumn({ type: 'string', role: 'style' });
data.addRows([
['Mac model 12', 200, 'color: #8bba30; opacity: 0.75;'],
['Another Mac Model', 110, 'color: #ffcc33; opacity: 0.75;'],
]);
var options = {
title: '',
width: 500,
height: data.getNumberOfRows() * 40 + 100,
hAxis: {
minValue: 0,
maxValue: 255,
ticks: [0, 75, 150, 255],
textPosition: 'out',
side: 'top'
},
series: {
0: { axis: 'Mac' },
1: { axis: 'Score' }
},
chartArea: {
top: 0,
bottom: 50,
right: 50,
left: 150
},
legend: { position: 'none' },
fontSize: 12,
bar: {groupWidth: '75%'},
};
var chart = new google.visualization.BarChart(document.getElementById('apple_div'));
chart.draw(data, options);
}
This is the output:
See, there are different colors for different bars. But I want different color and/or background-color for different legends on left side.
Can someone help me with this please?
I found following answer, Is it possible to show each legend in different color in google pie chart.
But it suggests on breaking down the chart(i.e. to draw separate charts for each rows), which is not desirable as there are large numbers of rows.
Not sure what you mean by breaking the chart, but...
You can modify the chart svg, once the 'ready' event fires.
This example changes the color of the legend text to match the bar color.
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var colors = ['#8bba30', '#ffcc33'];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Mac');
data.addColumn('number', 'Score');
data.addColumn({ type: 'string', role: 'style' });
data.addRows([
['Mac model 12', 200, 'color: ' + colors[0] + '; opacity: 0.75;'],
['Another Mac Model', 110, 'color: ' + colors[1] + '; opacity: 0.75;'],
]);
var options = {
title: '',
width: 500,
height: data.getNumberOfRows() * 40 + 100,
hAxis: {
minValue: 0,
maxValue: 255,
ticks: [0, 75, 150, 255],
textPosition: 'out',
side: 'top'
},
series: {
0: { axis: 'Mac' },
1: { axis: 'Score' }
},
chartArea: {
top: 0,
bottom: 50,
right: 50,
left: 150
},
legend: { position: 'none' },
fontSize: 12,
bar: {groupWidth: '75%'},
};
var chartContainer = document.getElementById('apple_div');
var chart = new google.visualization.BarChart(chartContainer);
google.visualization.events.addListener(chart, 'ready', function () {
var labels = chartContainer.getElementsByTagName('text');
var colorIndex = 0;
for (var i = 0; i < labels.length; i++) {
if (labels[i].getAttribute('text-anchor') === 'end') {
labels[i].setAttribute('fill', colors[colorIndex]);
colorIndex++;
}
}
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="apple_div"></div>
As for background color, SVG elements do not have background
so you would have to draw your own rect for that...
I have a google chart as follows which plots Age for various IDs. However, as age cannot be negative, I want it to be only on the positive axis.
I have given the minValue for vertical axis as 0, however it still shows the negative axis. How can I fix this?
My code below
function AgeChart() {
google.load("visualization", "1", {packages:["corechart"]});
var age_data = new google.visualization.DataTable();
var divname = "agediv";
age_data.addColumn('number', 'ID');
age_data.addColumn('number', 'Age');
age_data.addRow([1,10]);
age_data.addRow([1,20]);
age_data.addRow([1,30]);
age_data.addRow([1,40]);
age_data.addRow([1,50]);
var options = {'title':'Age line graph',
curveType: 'function',
viewWindowMode:'explicit',
vAxis: {title: 'Age (years)',
minValue: 0,
},
hAxis: {title: 'ID'},
height: 600,
width: 1000
};
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(age_data, options);
}
EDIT: After adding the viewWindow.min value, it works for me.
function AgeChart() {
google.load("visualization", "1", {packages:["corechart"]});
var age_data = new google.visualization.DataTable();
var divname = "agediv";
age_data.addColumn('number', 'ID');
age_data.addColumn('number', 'Age');
age_data.addRow([1,10]);
age_data.addRow([1,20]);
age_data.addRow([1,30]);
age_data.addRow([1,40]);
age_data.addRow([1,50]);
var options = {'title':'Age line graph',
curveType: 'function',
viewWindowMode:'explicit',
vAxis: {title: 'Age (years)',
minValue: 0,
viewWindowMode:'explicit',
viewWindowMode:'explicit',
viewWindow:{
min:0,
}
},
hAxis: {title: 'ID'},
height: 600,
width: 1000
};
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(age_data, options);
}
The minValue and maxValue may be used to extend the axis to include those values, but they do not restrict the axis to those values. What you want to do instead is use the viewWindow.min value.
On the date 26/10/2015 the actual version of Google charts requires only the following to stop displaying the negatives on the vertical axis.
var options = {
hAxis: { title: 'Dates',
},
vAxis: { title: 'Count of something',
viewWindow:{min:0},
},
};
As an option you can set up min value for more than 0 - it will give you same view.
vAxis: { title: 'Count',
minValue: 2,
},