Why is google pie chart showing up blank? - javascript

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"}]}]}

Related

how to create line chart with jqplot using ajax data

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

Turning Google trend visual query into Google GEOchart

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>

is not a function within the class

I am working on a small class to handle Google Chart and for some odd reason I keep getting
googleChart.js:86 Uncaught TypeError: this.swapChart is not a function
On the page I have a button with id "btnSwitch", click on which triggers a switch of the chart from chart view to the table view and vice-versa. This is defined within this.addChartSwitchListener() and called within this.init_chart()
I can call this.swapChart() within init method so I have to assume that issue is with:
_button.addEventListener('click', this.switchChart, false);
Here is my code below:
google.load('visualization', '1.0', {'packages': ['charteditor', 'controls']});
//google.setOnLoadCallback(drawDashboard);
var GChart = GChart || (function () {
var _graphType;
var _minTime;
var _maxTime;
var _hAxisTitle;
var _vAxisTitle;
var _tableData;
var _data;
var _dashboard;
var _lineChart;
var _button;
var _showChart;
return {
init: function (tableData, graphType, minTime, maxTime, hAxisTitle, vAxisTitle) {
// google charts
//_google = google;
_tableData = tableData;
// load chart params
_graphType = graphType;
_minTime = minTime;
_maxTime = maxTime;
_hAxisTitle = hAxisTitle;
_vAxisTitle = vAxisTitle;
// some other initialising
this.build_googlechart();
},
build_googlechart: function ()
{
this.init_chart();
// also tried this - with the same result.
// google.load('visualization', '1.0', {'packages':['corechart'], 'callback': this.drawChart});
},
init_chart: function ()
{
// var data = new google.visualization.DataTable();
_data = new google.visualization.DataTable(_tableData);
// Create a dashboard.
_dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));
if (_graphType === 'LineChart') {
this.lineChart();
} else {
this.columnChart();
}
this.addChartSwitchListener();
},
addChartSwitchListener: function ()
{
_button = document.getElementById('btnSwitch');
_button.addEventListener('click', this.switchChart, false);
_showChart = "Chart";
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(_lineChart, 'ready', function () {
if (_showChart !== 'Table') {
$('.save_chart').show();
$('.save_chart').removeClass('disabled');
$('.save_chart').attr('href', _lineChart.getChart().getImageURI());
$('#filter_div').show();
} else {
$('.save_chart').hide();
$('#filter_div').hide();
}
});
},
swapChart: function ()
{
var chart = "Table";
if (_showChart === "Chart") {
chart = _graphType;
}
_lineChart.setChartType(chart);
_lineChart.setOptions(this.getOptions(_showChart));
_lineChart.draw();
},
switchChart: function ()
{
_showChart = _button.value;
this.swapChart();
_showChart = (_showChart === 'Table') ? 'Chart' : 'Table';
_button.value = _showChart;
},
getOptions: function (chartType)
{
var options;
switch (chartType) {
case 'Chart':
options = {
backgroundColor: {
fill: 'transparent'
},
legend: 'right',
pointSize: 5,
crosshair: {
trigger: 'both'
},
hAxis: {
},
vAxis: {
}
};
break;
case 'Table':
options = {
showRowNumber: true,
width: '100%',
height: '100%'
};
break;
default:
options = {};
}
return options;
},
lineChart: function ()
{
var lineChartRangeFilter = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'filter_div',
'options': {
filterColumnIndex: 0,
ui: {
chartType: 'LineChart',
chartOptions: {
backgroundColor: {fill: 'transparent'},
height: '50',
chartArea: {
width: '90%'
}
}
}
}
});
// Create a pie chart, passing some options
_lineChart = new google.visualization.ChartWrapper({
'chartType': "LineChart",
'containerId': 'chart_div',
'options': {
backgroundColor: {fill: 'transparent'},
'legend': 'right',
'pointSize': 5,
crosshair: {trigger: 'both'}, // Display crosshairs on focus and selection.
hAxis: {
title: _hAxisTitle,
viewWindow: {
min: _minTime,
max: _maxTime
},
},
vAxis: {
title: _vAxisTitle
}
}
});
// Establish dependencies, declaring that 'filter' drives 'pieChart',
// so that the pie chart will only display entries that are let through
// given the chosen slider range.
_dashboard.bind(lineChartRangeFilter, _lineChart);
// Draw the dashboard.
_dashboard.draw(_data);
},
columnChart: function () {
_lineChart = new google.visualization.ChartWrapper({
'chartType': "ColumnChart",
'containerId': 'chart_div',
'dataTable': _data,
'options': {backgroundColor: {fill: 'transparent'},
'legend': 'right',
'pointSize': 5,
crosshair: {trigger: 'both'}, // Display crosshairs on focus and selection.
hAxis: {
title: _hAxisTitle,
},
vAxis: {
title: _vAxisTitle,
}
}
});
_lineChart.draw();
}
};
}());
This is because you pass a reference to that method to addEventListener, which will later be called with the window object as context, and not your this object.
To overrule this behaviour, you can use several solutions, but here is one with bind():
_button.addEventListener('click', this.switchChart.bind(this), false);

Google line chart is not working

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 ?

Google pie chart shows opposite colors

I have a pie chart that looks like this in the javascript:
function drawCurrentPieChart(title,days) {
var name = document.getElementById("dropdownSubCategories").value;
$
.ajax({
url : "piechartlist/",
type : "GET",
aync : true,
dataType : "json",
data : {days:days,
categoryName : name + ""},
error : function(e) {
alert(e.message + "ERROR ");
},
success : function(response) {
var jsonData = response;
if (response == "") {
alert("Error: Threshold is not valid or there is no status in the database within 24 hours.");
} else {
var data = [["Count","Color"]], colors = [];
for(var c in jsonData){
data[data.length] = [jsonData[c]["color"],jsonData[c]["count"]];
colors[colors.length] = jsonData[c]["color"];
}
data = google.visualization.arrayToDataTable(data);
var options = {
title: title,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'},
backgroundColor: 'transparent',
colors : colors
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'+days));
chart.draw(data, options);
}
}
});
When it draws the chart, it shows the opposite colors that it recieves from the database (green is red, red is green etc.) What can be the problem?

Categories