not enough columns to draw -google charts - google-visualization

I have tried to pass some array data to google charts but it says not enough columns to draw chart.here is my code.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var someStr = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data1=someStr.replace(/(["'])(\d+)\1/g,"$2")
console.log(data1);
var data = google.visualization.arrayToDataTable([['year'],[data1]]);
console.log(data);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
</body>
</html>
Please help me to do this.
Thank in advance.

Your data has two columns: Month and a Number. ("JAN","1088626")
But you're only providing a header for one column: year
Plus, you need to pass an actual array to arrayToDataTable. (not a string)
Try something like this...
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var someStr = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data1 = JSON.parse('[' + someStr.replace(/(["'])(\d+)\1/g,"$2") + ']');
// data array - add two column headings to data1
data1.splice(0, 0, ['month', 'number']);
// data table
var data = google.visualization.arrayToDataTable(data1);
// chart options
var options = {
title: 'My Daily Activities',
is3D: true
};
// chart
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>

You are getting this error since invalid input data is passed into google.visualization.arrayToDataTable function. The provided regex /(["'])(\d+)\1/g fails while parsing the input string, i would suggest to parse input string with JSON.parse function.
google.visualization.PieChart object expects data to be provided in
the following format:
var data = google.visualization.arrayToDataTable([
['Name', 'Value'],
['<name1>', <value1>],
['<name2>', <value2>],
['<name3>', <value3>],
...
['<namen>', <valuen>]
]);
Below is provided the modified example:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var stringData = '["JAN","1088626"],["FEB","1478093"],["MAR","1232870"],["APR","1151634"],["MAY","1083623"],["JUN","740591"],["JUL","769227"],["AUG","1162995"],["SEP","951794"],["OCT","884736"],["NOV","500902"],["DEC","1221438"]';
var data = JSON.parse("[" + stringData + "]");
data = data.map(function (item) {
item[1] = parseInt(item[1]);
return item;
});
data.splice(0, 0, ['year', 'hours']);
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(dataTable, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>

Related

Chart js with json file from url

I am new here so please forgive my errors in asking. I am working on a personal project with json file from external url. But the graph does not shown up. Chrome compiler says that
Chart.min.js:12 Uncaught TypeError: t.ticks.map is not a function
Chart.min.js:12 Uncaught TypeError: Cannot read property 'initialize' of undefinedeventHandler # Chart.min.js:12(anonymous function) # Chart.min.js:12i.(anonymous function) # Chart.min.js:12
Note: Arrays are getting the values
(Sorry if I ask this wrong way I will try to improve my questions)
<html>
<head>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
var name;
var count;
$(document).ready(function () {
var jsonurl = "http://avare.pe.hu/veri2.json";
$.getJSON(jsonurl, function (json) {
name = json[0]['names'];
count = json[0]['count'];
for (var i = 0; i < 5; i++)
console.log(name[i] + count[i]);
});
})
var canvas = document.getElementById('myChart');
var dataSet = {
labels: name,
datasets: [
{
label: "My First dataset",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: count,
}
]
};
var option = {
animation: {
duration: 5000
}
};
var myBarChart = Chart.Bar(canvas, {
data: dataSet,
options: option
});
</script>
</body>
</html>
Issue comes from the async call to get the data. You start the chart initialization after this call but because it is async name and count will be undefined at the time you create the chart.
Quick fix is to place the chart creation inside the success callback of the getJSON
https://fiddle.jshell.net/leighking2/45x1f09v/

Hide text from Google GeoChart tooltip

I have a Google Geochart that is connected to a Google Spreadsheet. The aim of the chart is to show different categories of universities in our state and their locations. I have assigned values in the spreadsheet in order to have the appropriate marker color for the map to denote the categories.
My problem is that the text denoting the type (a number) is showing in the tooltip. (Example: tooltip shows "ABC University Type 3." I need to either hide this text, or create a string based on conditional logic so that, for example, Type 3 translates to "XYZ System" in the tooltip. Which do you think is the better way to do it, and can you provide guidance as to how to do this?
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.charts.load('current', { 'packages': ['geochart'] });
google.charts.setOnLoadCallback(drawMap);
function drawMap() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1m3ujxzPQJh3haReNDzGGF73Mh6-u6HxyCVPK_5MK2hw/gviz/tq?sheet=Sheet3");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {var data = response.getDataTable();
var options = {
//showTip: true,
mapType: 'styledMap',
useMapTypeControl: true,
resolution: 'provinces',
//displayMode: 'text',
//magnifyingGlass: {'enable': true, 'zoomFactor': '7'},
region: 'US-KY',
keepAspectRatio: true,
legend: 'none',
sizeAxis: { minValue: 1, maxValue: 3, minSize: 10, maxSize: 10 },
colorAxis: {colors: ['green', 'blue', 'purple'], values: [1, 2, 3]},
markerOpacity: 0.75,
tooltip: {showColorCode: false, isHTML: true, textStyle:{fontSize: 21}},
dataMode: 'markers'
};
var map = new google.visualization.GeoChart(document.getElementById('chart_div'));
map.draw(data, options);
};
</script>
<style type="text/css">
html, body {height: 100%;}
#chart_div {width: 100%; height: 100%;}
</style>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
You can use the DataView Class to change the formatted value of the Type column.
For instance, the value of the Type column in the DataTable looks like this...
{"v":3.0,"f":"3"}
With the DataView, change it to this...
{"v":3.0,"f":"XYZ System"}
We can also remove the column Label, to avoid seeing it in the tooltip.
See following example...
google.charts.load('current', {
callback: drawMap,
packages: ['geochart']
});
function drawMap() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1m3ujxzPQJh3haReNDzGGF73Mh6-u6HxyCVPK_5MK2hw/gviz/tq?sheet=Sheet3");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
// setup school type array
var schoolTypes = [
'ABC System',
'LMO System',
'XYZ System'
];
// create DataView from DataTable
var view = new google.visualization.DataView(data);
// set view columns, keep first three columns
// use calculated column for Type
view.setColumns([0, 1, 2, {
type: 'number',
label: '',
calc: function (dataTable, rowIndex) {
return {
v: dataTable.getValue(rowIndex, 3),
// get school type from array
f: schoolTypes[dataTable.getValue(rowIndex, 3) - 1]
}
}
}]);
var options = {
//showTip: true,
mapType: 'styledMap',
useMapTypeControl: true,
resolution: 'provinces',
//displayMode: 'text',
//magnifyingGlass: {'enable': true, 'zoomFactor': '7'},
region: 'US-KY',
keepAspectRatio: true,
legend: 'none',
sizeAxis: { minValue: 1, maxValue: 3, minSize: 10, maxSize: 10 },
colorAxis: {colors: ['green', 'blue', 'purple'], values: [1, 2, 3]},
markerOpacity: 0.75,
tooltip: {showColorCode: false, isHTML: true, textStyle:{fontSize: 21}},
dataMode: 'markers'
};
var map = new google.visualization.GeoChart(document.getElementById('chart_div'));
map.draw(view, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
ALSO -- Recommend including loader.js and jsapi only once per page

google chart get selected value

I am trying to get the selected value of a Google Table Chart. When the chart content is not filtered using the string filter, it returns the index of the selected row according to the DataTable, but when it is filtered using the string filter, it doesn't returns the correct issue.
To replicate the issue please do the following code
1. Run the below code
Select Aaron in the table. A message box will display its index as 5.
Type letter 'A' in the string filter. Now select the Aaron, it will return 0 which is a bug.
It should return the index of the row in the data table for 'Aaron' which is 5
<!DOCTYPE html>
<html>
<head>
<title>Google Developers</title>
<link rel="stylesheet" type="text/css" href="/_static/07491c0cdc/css/screen-docs.css" />
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400" type="text/css">
<script src="/_static/07491c0cdc/js/prettify-bundle.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script id="jqueryui" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js" defer async></script>
<script src="http://www.google.com/jsapi?key=AIzaSyCZfHRnq7tigC-COeQRmoa9Cxr0vbrK6xw"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/_static/07491c0cdc/js/framebox.js"></script>
</head>
<body class="docs slim framebox_body">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="stringFilter_dashboard_div" style="border: 1px solid #ccc">
<div id="stringFilter_control_div" style="padding-left: 2em"></div>
<div id="stringFilter_chart_div"></div>
</div>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart', 'table', 'gauge', 'controls']});
google.setOnLoadCallback(apiLoaded);
function apiLoaded() {
drawStringFilter();
}
function drawStringFilter() {
var dashboard = new google.visualization.Dashboard(
document.getElementById('stringFilter_dashboard_div'));
var control = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'stringFilter_control_div',
'options': {
'filterColumnIndex': 0
}
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'stringFilter_chart_div',
'options': {'height': '25em', 'width': '20em'}
});
google.visualization.events.addListener(chart,'select',tableSelectHandler);
function tableSelectHandler(){
var selectedItem = chart.getChart().getSelection()[0];
alert(selectedItem.row);
}
var data = google.visualization.arrayToDataTable([
['Name', 'Age'],
['Michael' , 12],
['Elisa', 20],
['Robert', 7],
['John', 54],
['Jessica', 22],
['Aaron', 3],
['Margareth', 42],
['Miranda', 33]
]);
dashboard.bind(control, chart);
dashboard.draw(data);
}
</script>
<script>
devsite.github.Link.convertAnchors();
window.prettyPrint();
</script>
</body>
</html>
This should work:
function tableSelectHandler(e){
var selectedItem = chart.getChart().getSelection()[0];
var true_selected = chart.getDataTable().getTableRowIndex(selectedItem.row)
alert(true_selected);
}
getTableRowIndex traces the row back to the datatable
Expanding on juvian's answer, you should test the selection length before trying to access any elements in the array, as the array may be empty (or contain multiple elements if more than one row is selected):
function tableSelectHandler(e){
var selection = chart.getChart().getSelection();
var dt = chart.getDataTable();
for (var i = 0; i < selection.length; i++) {
// colIndex is the index of the column you want to get data from
var value = dt.getValue(selection.row, colIndex);
}
}

Can any tell me how add two needles in Gauge graph Using Google charts

I want to display two values in a single gauge graph using two needles. How can I do that.
Can any one please suggest me of doing it.
I have tried with following code But I am not success full.
And I got this following error.
GET http://5.39.186.164/%7B%22cols%22:[%7B%22label%22:%22Q7%22,%22type%22:%22nu…r%22%7D],%22rows%22:[%7B%22c%22:[%7B%22v%22:43%7D,%7B%22v%22:21%7D]%7D]%7D 404 (Not Found)
<!--Load the AJAX API -->
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['gauge']});
</script>
<script type="text/javascript">
var gauge;
var gaugeData;
var gaugeOptions;
function drawGauge() {
//var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
//var obj = eval ("(" + response + ")");
$.getJSON('<?php echo json_encode($response); ?>', function(json) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
for (x in json) {
data.addRow([x, json[x]]);
}
//gaugeData = new google.visualization.DataTable(response);
gauge = new google.visualization.Gauge(document.getElementById('gauge'));
gaugeOptions = {
width: 2000,
height: 150,
greenFrom: 0,
greenTo: 50,
redFrom: 75,
redTo: 100,
yellowFrom:50,
yellowTo: 75,
minorTicks: 5
};
gauge.draw(gaugeData, gaugeOptions);
//chart.draw(data, options);
});
}
google.load('visualization', '1', {packages:['gauge'], callback: drawGauge});

getSelection() to get data from row in Google Chart API

I'm trying to trigger the creation of a new BarChart with Google's Chart API when a user clicks on a particular bar. I think I understand the concepts, and wanted to at least get the getSelection() function to work and display what bar the user clicked on. But everytime, when you click on the bar, it just freezes with the display and no java alert. Any thoughts?
Here's the code:
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var visualization = new google.visualization.BarChart(document.getElementById('acctmeta'));
var json_data = new google.visualization.DataTable({{acctmeta_json}});
visualization.draw(json_data, {width: 850, height: 600, title: 'Collection Level Populated Metadata Fields',
chartArea: {width:"50%"},
vAxis: {title: 'Collection Title/ID', titleTextStyle: {color: 'green'}},
hAxis: {logScale:false, title:'Fields Populated', titleTextStyle: {color: 'green'}}
});
// Add our selection handler.
google.visualization.events.addListener(visualization, 'select', selectHandler);
// The selection handler.
// Loop through all items in the selection and concatenate
// a single message from all of them.
function selectHandler() {
alert(data.getValue(chart.getSelection()[0].row, 0));
}
} //end of draw chart function
</script>
Just wondering, should the line
alert(data.getValue(chart.getSelection()[0].row, 0));
be
alert(data.getValue(visualization.getSelection()[0].row, 0));
?
Here is a working example of mine. I had to set data and chart as global variables:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
var data;
var chart;
function drawChart() {
data = new google.visualization.DataTable();
data.addColumn('string', 'Where');
data.addColumn('number', 'What');
data.addRows([['ABC',87],['ERT',70],['KLJ',38],['UPP',-67],['SSD',27],['UKG',42],['NUS',60],['WEB',96]]);
var options = {'title':'my chart','width':'600','height':'400','is3D':'true'};
chart = new google.visualization.ColumnChart(document.getElementById('test3_chart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler2);
}
function selectHandler2() {
var selection = chart.getSelection();
alert('That\'s column no. '+selection[0].row);
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id=test3_chart>Please wait...</div>
</body>
</html>