Unable to populate Google Graph Line Chart - javascript

Below is how I populate it but it is not working:
var data = new google.visualization.DataTable();
var newData =[];
for(var j = 0; j<dates.length;j++){
newData.push([dates[j],close[j]]);
document.write(newData[j] + "<br>");
}
// determine the number of rows and columns.
var numRows = newData.length;
var numCols = newData[0].length;
data.addColumn('number', 'Date');
data.addColumn('number', 'Close');
// now add the rows.
for (var j = 0; j < numRows; j++){
data.addRow(newData[j]);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Closing Price'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
newData values are as below when printed out:
20151229,108.74
20151228,106.82
20151224,108.03
20151223,108.61
20151222,107.23
It shows no error and no graph is showing out. What could be wrong in the code above ?

function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
So since you have only 2 columns, you can completely get rid of the 3rd expenses.

Related

Why would I have to do chart.draw twice to get a Google pie chart to display?

I have a page in an app that displays all sorts of ticket metrics from several different ticketing systems we use. I use the same function to build each of the charts and display them:
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
}
This works for 13 of the 14 charts displayed on the page. 8 Columns and 5 out of 6 pie charts all display perfectly. One of the pie charts will ONLY display if I draw the chart a second time.
function drawChart(chartData, chartStyle, chartTitle, chartSpanID) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Hour');
data.addColumn('number', 'Tickets');
data.addRows(chartData);
if(chartStyle == "column"){
var chart = new google.visualization.ColumnChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,chartArea: {left: 30, top:20, bottom:30, right:10},animation:{startup: true, duration:2000}}
};
if(chartStyle == "pie"){
var chart = new google.visualization.PieChart(document.getElementById(chartSpanID));
var options = {title:chartTitle,
chartArea:{left: 0, top:20, bottom:10, right: 0},
is3D: true,
sliceVisibilityThreshold: .01,
animation:{startup: true,easing: 'in', duration:1000},
pieResidueSliceLabel: "Other( < 1%)"};
};
chart.draw(data, options);
chart.draw(data, options);
}
The data is delivered correctly, all calls are made through google.charts.setOnLoadCallback, it all works just fine once called again... so why is it only working on the second call? Why just the one chart that doesn't display as expected? What have I missed?

Loop Google Chart Data Rows

I have my data in the below format, below is just a sample
var data = google.visualization.arrayToDataTable([
['Medium', 'Expenses'],
['Twitter', 400],
['Facebook', 460],
['Youtube', 1120],
['Instagram', 540]
]);
I want to loop through the records and give appropriate color to each platform.
I know it can be done for columns like below:
var view = new google.visualization.DataView(data);
var colors = [];
for (var i = 1; i < view.getNumberOfColumns(); i++) {
switch (view.getColumnLabel(i)) {
case "Twitter":
colors = colors.concat(["#26CEFF"]);
break;
}
I provide this to the chart in options as below:
var options = {
colors: colors
}
var chart = new google.visualization.PieChart(Div);
chart.draw(view, options);
But I am unable to loop through the rows to do the same functionality. Help appreciated.
Note: I cannot add the color property while creating the datatable. I have to do the functionality after creating the view or datatable only.
for a pie chart, you can loop using --> data.getNumberOfRows()
build the colors array based on the value of the first column --> Medium
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Medium', 'Expenses'],
['Twitter', 400],
['Facebook', 460],
['Youtube', 1120],
['Instagram', 540]
]);
var colors = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
switch (data.getValue(i, 0)) {
case 'Twitter':
colors.push('#26CEFF');
break;
case 'Facebook':
colors.push('blue');
break;
case 'Youtube':
colors.push('red');
break;
case 'Instagram':
colors.push('green');
break;
}
}
var options = {
colors: colors
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(container);
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
for column or bar charts, the colors option won't work.
if there is only one series --> 'Expenses'
instead, need to use a 'style' role in the data table / view.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Medium', 'Expenses'],
['Twitter', 400],
['Facebook', 460],
['Youtube', 1120],
['Instagram', 540]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: function (dt, row) {
var color;
switch (dt.getValue(row, 0)) {
case 'Twitter':
color = '#26CEFF';
break;
case 'Facebook':
color = 'blue';
break;
case 'Youtube':
color = 'red';
break;
case 'Instagram':
color = 'green';
break;
}
return color;
},
type: 'string',
role: 'style'
}]);
var options = {
legend: 'none'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

How to print the bottom label of google gauge outside the guage?

I am trying to print the bottom label of the Google gauges outside(just below the respective gauges). Also, I want to provide two different suffixes for the two gauges. I have tried giving separate formatters(formatter1, formatter2) for both and separate data(data1 and data2), but it's not even drawing the gauges(no error). In this case, the draw_data_guage will have a fourth argument.
var e = document.getElementById('draw_chart');
e.onclick = draw_data_gauge(80, 68, '%');
function draw_data_gauge(cpu_data, memory_data, suffix) {
console.log("in guage")
google.charts.load('current', {
'packages': ['gauge']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Label', 'Value'],
['CPU', cpu_data],
['Memory', memory_data],
]);
var options = {
width: 500,
height: 150,
redFrom: 90,
redTo: 100,
yellowFrom: 75,
yellowTo: 90,
minorTicks: 5,
};
var formatter1 = new google.visualization.NumberFormat({
suffix: suffix,
});
formatter1.format(data1, 1);
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data1, options);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<input name="Button" type="button" value="Draw" id="draw_chart" />
<div id="chart_div"></div>
I want the gauge's bottom label to be displayed outside and be able to give separate suffixes for both the gauges. Consider this jsfiddle link. I want to display the percentages(bottom label) outside the gauges just below them. My jsfiddle link is here. Thanks in advance.
Your direction to separate the graphs is right. Here is how to do this:
div {
display: inline-block;
}
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type="text/javascript">
google.load('visualization', '1', {
packages: ['gauge']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
width: 400,
height: 120,
redFrom: 90,
redTo: 100,
yellowFrom: 75,
yellowTo: 90,
minorTicks: 5
};
var source = [{
data: ['Memory', 80],
suffix: '%'
},
{
data: ['CPU', 55],
suffix: '?'
},
{
data: ['Network', 68],
suffix: '$'
},
];
source.map((item, index) => {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
item.data
]);
var formatter = new google.visualization.NumberFormat({
suffix: item.suffix,
fractionDigits: 0
});
formatter.format(data, 1);
document.body.innerHTML += '<div id="chart_div_' + index + '"></div>';
var chart = new google.visualization.Gauge(document.getElementById('chart_div_' + index));
chart.draw(data, options);
});
// dynamic update, randomly assign new values and redraw
//setInterval(function() {
// data.setValue(0, 1, 40 + Math.round(60 * Math.random()));
// formatter.format(data, 1);
// chart.draw(data, options);
//}, 1000);
//
//setInterval(function() {
// data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
// chart.draw(data, options);
//}, 1000);
//
//setInterval(function() {
// data.setValue(2, 1, 40 + Math.round(60 * Math.random()));
// chart.draw(data, options);
//}, 1000);
}
</script>
About the text position, I think that it's impossible. You can add a div below each chart with the text.

Google Charts Get maximum scale

I'm trying to make an all positive bubble chart have quadrants by drawing the quadrants using the baseline property like so:
var dataT = google.visualization.arrayToDataTable(.....);
var options = {
hAxis: {title: 'h axis',baseline:100},
vAxis: {title: 'v axis',baseline:20},
...}
var chart = new google.visualization.BubbleChart(...);
chart.draw(dataT,options);
Except the graph will keep changing depending on the query so the baselines will not be the same for all the graphs. I would like to be able to get the max axis value and divide it by 2 to set the baselines right in the middle of each axis.
Example:
var options = {
hAxis: {title: 'h axis',baseline:max_h_axis/2},
vAxis: {title: 'v axis',baseline:max_v_axis/2},
...
Is there any way of knowing the max axis values of the graph before drawing the graph?
the getColumnRange method works for this...
Returns the minimal and maximal values of values in a specified column. The returned object has properties min and max. If the range has no values, min and max will contain null.
you can also use this information to produce your own axis tick marks.
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['X', 'Y'],
[8, 120],
[4, 155],
[11, 140],
[4, 205],
[3, 35],
[6, 78]
]);
var ticksX = [];
var ticksY = [];
var numberOfTicks = 10;
var rangeX = data.getColumnRange(0);
var rangeY = data.getColumnRange(1);
var stepX = Math.ceil((rangeX.max - rangeX.min) / numberOfTicks);
for (var i = rangeX.min - stepX; i <= rangeX.max + stepX; i = i + stepX) {
ticksX.push(i);
}
var stepY = Math.ceil((rangeY.max - rangeY.min) / numberOfTicks);
for (var i = rangeY.min - stepY; i <= rangeY.max + stepY; i = i + stepY) {
ticksY.push(i);
}
var baseX = Math.ceil((rangeX.max - rangeX.min) / 2) + rangeX.min;
var baseY = Math.ceil((rangeY.max - rangeY.min) / 2) + rangeY.min;
var options = {
hAxis: {
title: 'h axis',
baseline: baseX,
ticks: ticksX
},
vAxis: {
title: 'v axis',
baseline: baseY,
ticks: ticksY
},
legend: 'none',
height: 600,
width: 600
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Make Two Google charts in the same page

I am triying to put two google charts of the same style, but when i try it, one is visible and one didnt appear.
So, here's the code.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales'],
['2014', 1000],
['2015', 1170],
['2016', 660],
['2017', 1030]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
What variables I need to change to make an other chart like this??
the script is looking for the id selector, in html the id is unique
so add a new div with antoher id and at the end of your script do
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
var chartOther = new google.charts.Bar(document.getElementById('columnchart_material_other'));
chart.draw(data, options);
chartOther.draw(data, options );
if you want to use a classname you could draw the same charts for all elements with class some like this:
var charts = document.getElementsByClassName("yourclass");
for (var i = 0; i < charts; i++) {
var chart = new google.charts.Bar(charts[i]);
chart.draw(data, options);
};

Categories