I'm working first time with google chart.i am trying to modify a bar chart to line chart in which i am facing an error "container is not defined". As a bar chart it is working fine and i am taking data as a json response my json response is like this.
[{"rate":0.7955,"month":"December"},{"rate":0.7822,"month":"November"},{"rate":0.7789,"month":"October"},{"rate":0.7915,"month":"September"},{"rate":0.7928,"month":"August"},{"rate":0.8002,"month":"July"},{"rate":0.8133,"month":"June"},{"rate":0.8218,"month":"May"},{"rate":0.8264,"month":"April"},{"rate":0.823,"month":"March"},{"rate":0.8201,"month":"February"},{"rate":0.8297,"month":"January"}]
and my js file is
var TUTORIAL_SAVVY = {
/*return google visualization data*/
getvisualizationData: function (jsonData) {
var point1, dataArray = [],
data = new google.visualization.LineChart();
data.addColumn('string', 'Rate');
data.addColumn('number', 'Marks in Mathematics');
data.addColumn({
type: 'string',
role: 'tooltip',
'p': {
'html': true
}
});
/* for loop code for changing inputdata to 'data' of type google.visualization.DataTable*/
$.each(jsonData, function (i, obj) {
point1 = "Rate : " + obj.rate + "";
dataArray.push([obj.month, obj.rate, TUTORIAL_SAVVY.returnTooltip(point1)]);
});
data.addRows(dataArray);
return data;
},
/*return options for line chart: these options are for various configuration of chart*/
getOptionForLinechart: function () {
var options = {
title:'Key Success Metrics over time across all channels',
'backgroundColor': 'transparent',
'width': 620,
'vAxis': {minValue:"0", maxValue:"100", gridlines:{count: 7} },
'chartArea': {top:"50", left: "40"},
'legend':{position: 'top', alignment: 'start' }
};
return options;
},
/*Draws a line chart*/
drawLineChart: function (inputdata) {
var lineOptions = TUTORIAL_SAVVY.getOptionForLinechart(),
data = TUTORIAL_SAVVY.getvisualizationData(inputdata),
chart = new google.visualization.LineChart(document.getElementById('student-line-chart'));
chart.draw(data, lineOptions);
/*for redrawing the line chart on window resize*/
$(window).resize(function () {
chart.draw(data, lineOptions);
});
},
/* Returns a custom HTML tooltip for Visualization chart*/
returnTooltip: function (dataPoint1) {
return "<div style='height:30px;width:150px;font:12px,roboto;padding:15px 5px 5px 5px;border-radius:3px;'>" +
"<span style='color:#68130E;font:12px,roboto;padding-right:20px;'>" + dataPoint1 + "</span>" ;
},
/*Makes ajax call to servlet and download data */
getStudentData: function () {
$.ajax({
url: '/bin/servlet/rate',
dataType: "JSON",
success: function (data) {
TUTORIAL_SAVVY.drawLineChart(data);
}
});
}
};
google.load("visualization", "1", {
packages: ["corechart"]
});
$(document).ready(function () {
TUTORIAL_SAVVY.getStudentData();
});
can anybody help ?
Related
I am trying to create line chart with Jqplot by getting the data from c# controller using ajax.
function getGraph(fcn) {
var turl = '/Rep/ChartBoxPlot/' + fcn;
$.ajax({
type: "POST",
url: turl,
dataType: "json",
success: function (result) {
$('#chart1').empty();
for (var i = 0; i < result.length; i++) {
var temp = result[i]['Date'];
var date = moment(temp).format('MMM DD');
var y = result[i]['Actual'];
var line1 = [date, result[i]['Actual']];
var line2 = [date, result[i]['Forecast']];
// alert(line1);
var plot = $.jqplot('chart1', [line1], {
axes: {
xaxis: {
label: "Forecast",
renderer: $.jqplot.ajaxDataRenderer,
//tickOptions: { formatString: '%I:%M:%S %p' },
//numberTicks: 8,
tickInterval: '15 second'
},
yaxis: {
label: 'Lines'
},
},
});
}
},
error(result) {
alert(result)
}
});
}
html
<div id="chart1" style="height: 400px; width: 900px;
position: relative;" class="jqplot-target">
The data from controller is coming fine but the graph is not plotted. Any suggestions would be appreciated
Thanks
Am a beginner using google charts/js. My google chart below loads fine, however there are times when the chart area loads blank html, and when I refresh the page it displays correctly.
I'm not sure why this is. It seems to do this on all browsers. This seems to indicate it could be with Mozilla, but the problem persists...
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei.' '. $end.' '.$start); #imei=sys.arg[1] end=sys.arg[2] start=sys.arg[3]
?>
var jsonData = <?php echo $result; ?> //{"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {0: {viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
$(window).resize(function(){
drawChart()
});
});
</script>
when using a function inline / anonymously, although you can provide a name,
you will not be able to call that same function again, by it's name
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() { // <-- cannot call this again, no name needed
...
instead, declare the function separately, then pass a reference where needed,
using the name of the function
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
...
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
var jsonData = {"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {
0: {
viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {
viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {
0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_chart"></div>
I have this json output from the file countrows.php:
[
{
"time_stamp":"08:22:46 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:22:50 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:22:54 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:22:57 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:23:01 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:23:05 am",
"ph":"8",
"moist":"0"
},
{
"time_stamp":"08:23:09 am",
"ph":"8",
"moist":"0"
}
]
The thing here is I want to show the time(coming from my json file) in my chart, specifically in the horizontal side. Something like the image below but the yellow green line shows the time from my json file.
By the way the following is my javascript code in my google chart,I need help on what to do with the following code:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
// onload callback
function drawChart() {
// JSONP request
var jsonData = $.ajax({
url: 'countrows.php',
dataType: 'json',
}).done(function (results) {
var data = new google.visualization.DataTable(jsonData);
data.addColumn('datetime', 'time_stamp');
data.addColumn('number', 'ph');
data.addColumn('number', 'moist');
$.each(results, function (i, row) {
data.addRow([
new Date(row.time_stamp),
parseFloat(row.ph),
parseFloat(row.moist)
]);
});
var chart = new google.visualization.AreaChart($('#chart').get(0));
chart.draw(data, {
title: 'Soil Analysis',
curveType: 'function',
displayAnnotations: true,
//legend: { position: 'bottom' }
pointSize: 10
hAxis: {format: 'Y,M,d,H';}
});
});
}
drawChart();
setInterval(drawChart, 10000);
the easiest way would be to change the first column to --> 'string'
data.addColumn('string', 'time_stamp');
also, since ajax is async, no need to assign to a variable,
remove this --> var jsonData =
and remove from argument to the data table constructor...
var data = new google.visualization.DataTable(jsonData); // <-- remove jsonData
try following snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
// onload callback
function drawChart() {
$.ajax({
url: 'countrows.php',
dataType: 'json'
}).done(function (results) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time_stamp');
data.addColumn('number', 'ph');
data.addColumn('number', 'moist');
$.each(results, function (i, row) {
data.addRow([
row.time_stamp,
parseFloat(row.ph),
parseFloat(row.moist)
]);
});
var chart = new google.visualization.AreaChart($('#chart').get(0));
chart.draw(data, {
title: 'Soil Analysis',
curveType: 'function',
pointSize: 10
});
});
}
drawChart();
setInterval(drawChart, 10000);
I'm trying to pass some data from the Google trends to a Google chart but i'm getting the Incompatible data table: Error: Table contains more columns than expected (Expecting 2 columns) error
I just assumed it would work automatically from one I query it into a chart rather than get an error. The code i'm getting an error with is:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var findTitle = $(".input-wrapper input").val();
function drawChart() {
console.log(findTitle);
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=GEO_MAP_0_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (data, row) {
return data.getFormattedValue(row, 0);
},
type: 'string',
label: data.getColumnLabel(0)
}, 1]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_region_top'));
chart.draw(view, {
chartArea: {
height: '80%',
width: '100%'
},
});
chart.draw(data, {
width: 1000,
height: 500,
title: 'Tag: Battlefield 1',
colors: ['#ff0000'],
backgroundColor: '#2D2D2D',
legendTextStyle: { color: '#FFF', position: 'bottom' },
titleTextStyle: { color: '#FFF' },
hAxis: {
textStyle: {color: '#FFF'},
gridlines: {color: '#FFF'}
},
vAxis: {
textStyle: {color: '#FFF'},
gridlines: {color: '#FFF'}
}
});
});
}
Any help into why i'm getting this error and a solution is greatly appreciated :)
since the GeoChart expects two columns,
use a DataView to extract the first two columns from the DataTable
also, need to load 'geochart' package, see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['geochart']
});
function drawChart() {
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=GEO_MAP_0_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
var view = new google.visualization.DataView(response.getDataTable());
view.setColumns([0, 1]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(view, {
legend: 'none'
});
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I am trying to load a pie chart. I have other charts on the page (4 column and 2 Dual-Y Columns) and they are loading correctly, but the pie chart comes out blank. I get no error messages. Why is it showing up blank? What am I missing?
function insert_graph(graph_data_type, location, title, type, horizontal_axis, vertical_axis, height) {
$.ajax({
type: 'get',
url: 'getdata.php?id=' + id+ '&graph=' + graph_data_type,
dataType: 'json',
success: function (response) {
if (response === 'error') {
//Error Handling
} else if (null === response) {
//Error Handling
} else {
chart_data = response;
google.charts.setOnLoadCallback(function () {
drawGoogleGraph(response, location, title, type, horizontal_axis, vertical_axis,height);
});
}
}
});
}
function drawGoogleGraph(chart_data, chart_location, chart_title, chart_type, horizontal_axis, vertical_axis,height) {
var data = new google.visualization.DataTable(chart_data);
switch (chart_type) {
case 'column':
var options = {
title: chart_title,
height: height,
hAxis: horizontal_axis,
vAxis: vertical_axis
},
chart = new google.visualization.ColumnChart($('#' + chart_location)[0]);
break;
case 'column_dual_y':
var options = {
title: chart_title,
height: height,
hAxis: horizontal_axis,
vAxis: vertical_axis,
series: {
0: {axis: 'cytd'},
1: {axis: 'pytd'}
}
},
chart = new google.visualization.ColumnChart($('#' + chart_location)[0]);
break;
case 'pie_3d_exploding':
var options = {
title: chart_title,
is3D: true,
height: height,
hAxis: horizontal_axis,
vAxis: vertical_axis
},
chart = new google.visualization.PieChart($('#' + chart_location)[0]);
break;
}
chart.draw(data, options);
}
And the data returned from a PHP Script
{"cols":[{"id":"product_type","label":"product_type","type":"string"},{"id":"cases","label":"cases","type":"number"}],"rows":[{"c":[{"v":"COFF"}{"v":"36046.00"}]},{"c":[{"v":"COCO"},{"v":"710.00"}]},{"c":[{"v":"TEA"},{"v":"635.00"}]},{"c":[{"v":"NA"},{"v":"156.00"}]},{"c":[{"v":"DAIR"},{"v":"155.00"}]},{"c":[{"v":"BRWR"},{"v":"149.00"}]},{"c":[{"v":"FRUI"},{"v":"70.00"}]},{"c":[{"v":"ACC"},{"v":"2.00"}]}]}