google chart api draws negative axis as well though minValue is 0 - javascript

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,
},

Related

Google Chart columnChart haxis dates are wrong

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>

Dynamic Vertical Axis to Accommodate Trendline(s) in Google Line Chart

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...

Google Visualization API double Y axis - not being able to adjust targetAxisIndex

I am creating a multiple line chart with Google Chart API where I want to use 2 Y axis such as -> , but with one axis set to max 24000 for my 6 countries, and the second set to 90000 for the 'Total World' column.
The problem is that my set of options never returns the 'Total World' in the second y axis and the other 6 countries in the first y axis, no matter how I arrange the option 'targetAxisIndex':
var tot = 95000;
var min = 0, var max = 24000;
....
var options = {
title: 'Top Consuming Nations - Thousand barrels daily',
hAxis: {title: 'Year'},
width: 1050, height : 400,
vAxes: [
{title: 'Top Countries', titleTextStyle: {color: '#FF0000'}, maxValue: max}, // Left axis maxValue: 60000
{title: 'Total World', titleTextStyle: {color: '#FF0000'}, maxValue: tot} // Right
],
series:[
{targetAxisIndex:1},
{targetAxisIndex:0}
],
legend: { position: 'top', alignment: 'start' }
};
here is the complete code: http://plnkr.co/edit/u5xXExdkTTYU8fHxWzHB?p=preview
I found the answer on Google Groups:
Hi Chris,
The series option is supposed to be a mapping of series index to series options. When you specify it as an array, you're basically doing that assignment implicitly. So in your example, series 0 will go on axis 1, and series 1 will go on axis. All other series will go to the default axis (0). Your issue could be fixed pretty easily, by simply reorganizing your series such that the total is the first. Alternatively, you could explicitly specify that series 6 (your total series, 'country6') should go on axis 1. The default is for things to go on axis 0, so you don't need to explicitly specify that. Here's an updated version of your plunkr with the second version of the solution (since that was easier for me to do): http://plnkr.co/edit/GhsNcBCtDW0i4OTu0VJR?p=preview
var options = {
title: 'Top Consuming Nations - Thousand barrels daily',
hAxis: {title: 'Year'},
width: 1050, height : 400,
vAxes: [
{title: 'Top Countries', titleTextStyle: {color: '#FF0000'}, maxValue: max}, // Left axis maxValue: 60000
{title: 'Total World', titleTextStyle: {color: '#FF0000'}, maxValue: tot} // Right
],
series:{
6: {targetAxisIndex: 1}
},
legend: { position: 'top', alignment: 'start' }
};
var chart = new google.visualization.LineChart(document.getElementById(chartDiv));
chart.draw(data, options);

setting the vertical axis scale in google charts api

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);
}

Google Charts - Avoid showing negative values in yAxis

I have the following code:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'People'],
['2010',0]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
backgroundColor: 'none'
}
);
}
Which gives me the following chart
How can I do to avoid showing negative values in the yAxis? I have tried adding
vAxis: {minValue:0} without any luck.
There is a playground/sandbox for these charts: Google Charts Playground
​
You need to set viewWindowMode as explicit
vAxis: {viewWindowMode: "explicit", viewWindow:{ min: 0 }}
viewWindowMode: "explicit" is deprecated in current version which uses: vAxis.viewWindow.min:
vAxis: {
viewWindow: {
min: 0
}
}
It was not working form me. I needed to add the max value:max:1
The negative axis only appears if all the values are 0, so, for not bounding in the max, I only put the vAxis if there are no positives values (using PHP).
The example of my code is:
$hayPositivos = false;
foreach($valores as $valor){
$html[]=",
['".$valor['dia']."', ".intval($valor['validadas']).", ".intval($valor['totales'])."]";
if(!$hayPositivos && (intval($valor['validadas']) >0 || intval($valor['totales']) >0)){
$hayPositivos = true;
}
}
$html[]="]);
var options = {
title: '".t('News by time:').$periodo_nombre."',
legend: { position: 'bottom' }";
if(!$hayPositivos){
$html[] = ",
vAxis: {
viewWindow: {min: 0, max:1}
}";
}
$html[] = "};
And this is how it is seen:
If all values are negative
If there is any positive value

Categories