Google Annotation Chart load from CSV - javascript

I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:
https://developers.google.com/chart/interactive/docs/gallery/annotationchart
I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.
My code so far:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
$.get('test.csv', function(csvString)
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row)
{
return
[new Date(row[0]),row[1]];
});
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
CSV File
Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345

first, add jquery and jquery csv to your page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
then replace the code as follows.
see comments for explanations...
// load google charts
google.charts.load('current', {
packages: ['annotationchart']
}).then(function () {
// declare data variable
var arrayData;
// get csv data
$.get('test.csv', function(csvString) {
// get csv data success, convert to an array, draw chart
arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
drawChart(arrayData);
}).fail(function () {
// get csv data failed, draw chart with hard-coded data, for example purposes
arrayData = [
['Date','Value1'],
['2014-01-01',1233],
['2014-01-02',1334],
['2014-01-03',1488],
['2014-01-04',1888],
['2014-01-05',2011],
['2014-01-06',1900],
['2014-01-07',1768],
['2014-01-08',2345],
];
drawChart(arrayData);
});
});
// draw chart
function drawChart(arrayData) {
// convert string in first column to a date
arrayData = arrayData.map(function (row) {
return [new Date(row[0]),row[1]];
});
// create google data table, chart, and options
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
// draw chart
chart.draw(data, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: you can remove the fail callback, it is for example purposes here on stack overflow...

You need to follow 3 step for this task
Fire ajax request and take csv data
Convert csv data into array
Pass csv array in google graph
Please take refrence from following example:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
//Step 1: Get string from csv
$(document).ready(function () {
$.ajax({
type: "GET",
url: "test.csv",
dataType: "text",
success: function (data) {
//Step 2: Convert "," seprated string into array
let arrData = csvToArray(data);
//Step 3: call chart with array data
callChart(arrData);
}
});
});
//convert csv string into array function
function csvToArray(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1;i < allTextLines.length;i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0;j < headers.length;j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}
return lines;
}
function callChart(arrData) {
google.charts.load('current', { 'packages': ['annotationchart'] });
google.charts.setOnLoadCallback(function () { drawChart(arrData); });
}
function drawChart(arrData) {
var data = new google.visualization.DataTable();
//Step 4: add csv your column
data.addColumn('date', 'Date');
data.addColumn('number', 'Kepler-22b mission');
//Step 5: pass your csv data as array
data.addRows(arrData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>

Related

how to read data from an JSON file and pass it to google chart rows (javascript)

have the following function JSONChart()
it reads json data from var "allText" and should be able to parse the data and use it as row data for google charts.
Commenting out the adding row part displays the column data correctly with empty graph.
Need a way to parse the given sample data from a file and display it as row data in the google chart.
function JSONChart() {
google.charts.load('current', {'packages':['corechart']});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var data1 = JSON.parse(allText);
var dataTableData = google.visualization.arrayToDataTable(data1);
data.addRows (dataTableData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
// Set chart options
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
'width':1400,
'height':600,
curveType: 'function'
};
chart.draw(data, options);
}
window.onload = function() {
google.charts.setOnLoadCallback(JSONChart());
};
Sample JSON passed into variable "allText"
{"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}
a few things...
1) arrayToDataTable expects a simple array, not a json object
it also returns an entire data table, which has already been created --> data
instead, convert each json object to an array,
then use addRows to add the data to the existing data table --> data
something like...
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
2) google.charts.load -- this statement waits for the window / document to load, before calling the callback
no need for --> window.onload = function() {...
google.charts.load actually returns a promise,
so you can do something like...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// draw chart code here...
3) when passing a callback function to setOnLoadCallback,
a reference to the function should be passed --> JSONChart
not the result of a function --> JSONChart() (remove parens)
4) recommend similar setup as following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Time stamp');
data.addColumn('number', 'CPU');
data.addColumn('number', 'MEMORY');
data.addColumn({type:'string', role:'annotation'});
data.addColumn({type:'string', role:'annotationText'});
var chartData = [];
var data1 = {"2017/11/03 01:06:51":{"SCREEN":" ABC ","MEMORY":" 32.0142% ","CPU":" 9.1% "},"2017/11/03 02:22:20":{"SCREEN":" XYZ ","MEMORY":" 31.101% ","CPU":" 10.3% "}};
for (var date in data1) {
if (data1.hasOwnProperty(date)) {
chartData.push([
date,
parseFloat(data1[date].MEMORY.replace('%', '').trim()),
parseFloat(data1[date].CPU.replace('%', '').trim()),
data1[date].SCREEN,
'' // not sure what value you want to use here
]);
}
}
data.addRows(chartData);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {'title' : 'CPU & Memory',
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Percentage'
},
height: 600,
curveType: 'function'
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google charts javascript error

I'm trying to display a google pie chart from data recovered from excel sheet.
The returned String is described below which I'm passing in google.visualization.arrayToDataTable();
The code that I have used is:
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
//
var ss=[res];
document.write(ss); //the output of this is:
[['Solution','TOTAL'],['Check',23],['FULL',18],['POP',109]]
function drawChart() {
var data = google.visualization.arrayToDataTable(ss);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
This is showing error :
JavaScript runtime error: First row is not an array.
Please tell me what I'm doing wrong and how to correct it.
Thanks in advance.
`document.write(ss);`
Is only for this example, right? If it not so remove it and try to see inside your function what is the value of ss, like this-
function drawChart() {
console.write(ss);
var data = google.visualization.arrayToDataTable(ss);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Update
Try to rewrite your function drawChart() like this-
function drawChart() {
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
//
var ss=[res];
var data = google.visualization.arrayToDataTable(ss);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
Update 2
I created for you jsfiddle here jsfiddle, with your array in hard code, as you can see it is working here.So your problem is something with the server side or with the value of ss.
I think you need to parse the string into an array, try this...
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
var str = '<%= JSNstring %>'; //returned string from C#.
var res= str.replace(/""/g,"'");
res=res.replace(/"/g,"'");
var ss='[' + res + ']';
function drawChart() {
var data = google.visualization.arrayToDataTable(eval(ss));
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}

Google Visualization Charts ajax data

I'm trying to dynamically render a google visualization chart with an AJAX call in flask to set the data. User enters input then clicks a link which calls the ajax function to get the data. the "/ajax_test" view will return a json object but the problem I have is i don't know how to correctly pass the data back into the DataTable function. How do i pass the json data i'm getting from ajax to a variable for the drawchart function?
Chart function:
<script type="text/javascript">
function drawChart(){
var data = new google.visualization.DataTable(jsondata);
var options = {
explorer: {},
}; //end options
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Ajax function:
<script type=text/javascript>
$(function() {
$('a#DrawChart').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/ajax_test',
{//input data sent to view}
, function(data) {
var jsondata = data.test_json;
drawChart();
});
return false;
});
});
</script>
This method doesn't know where jsondata comes from:
function drawChart() {
var data = new google.visualization.DataTable(jsondata);
...
}
Add jsondata as a parameter:
function drawChart(jsondata) {
var data = new google.visualization.DataTable(jsondata);
...
}
And then in your Ajax call pass jsondata to the method:
function(data) {
var jsondata = data.test_json;
drawChart(jsondata);
}
I have done something similar using the following code, this is a jinja2 example, so you have do adapt your code (change the way jsonData var is initialized):
<script type="text/javascript">
//load the Google Visualization API and the chart
google.load('visualization', '1', {'packages': ['corechart']});
google.setOnLoadCallback (createChart);
var jsonData = {{ value_columns | tojson | safe }}
function createChart() {
var dataTable = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
//define options for visualization
var options = {is3D: 'no', title: 'Some Title' };
attachRedrawForTab(chart, dataTable, options);
attachRedrawForAccord(chart, dataTable, options);
//draw our chart
chart.draw(dataTable, options);
}
</script>

Passing values between two javascript in a html

I have a case where i need to load a char based on the input from another javascript. But it doesn't work in my case. I have added the code below:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url: fileURL, // make this url point to the data file
dataType: 'json',
cahce:false,
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title: graphTitle,
is3D: 'true',
width: 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
and I pass the value for graphtitle and fileURL as below:
<script type="text/javascript">
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor"){
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
}else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
}else{
document.getElementById('chart_div').style.display = "none";
}
}
</script>
Both these javascript are within the same file. I can't pass the fileURL and graphTitle when I used the above code. Any idea how to solve this issue?
Use global variables with window. E.g.
$(document).ready(function () {
window.fileURL = "";
window.graphTitle = "";
});
Don't specify "var" or it will only be within the scope of the function.
EDIT: Also make sure that the script in which your variables are assigned initially is before the other one.
How about something a bit more OO oriented (not really OO, but less inline code) ? It's cleaner and easier to read/maintain ..example could still use some work, but i"m sure you get the idea.
function loadChart(title, url) {
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart', 'table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var json = $.ajax({
url : url, // make this url point to the data file
dataType: 'json',
cahce : false,
async : false
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(json);
var options = {
title : title,
is3D : 'true',
width : 800,
height: 600
};
var tableOptions = {
title: 'App Listing'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(document).ready(function () {
var fileURL = "";
var graphTitle = "";
function showDiv() {
if($firstCheck) {
var selText;
$("#dd4 li a").show(function () {
selText = $(this).text();
});
if(selText !== "Factor") {
if(selText == "IA Architecture Usage"){
fileURL = "get_json.php";
graphTitle = "IA Architecture Variation";
} else if(selText == "Tablet to Phone"){
fileURL = "get_tablet_support.php";
graphTitle = "Tablet Usage Variation";
}
document.getElementById('chart_div').style.display = "block";
}
} else {
document.getElementById('chart_div').style.display = "none";
}
loadChart(graphTitle, fileURL);
}
}
btw i think you have an error in your code: .responseText seems pretty useless to me, and most likely throws an error in itself. Also i have no idea who is calling showDiv() in the code. From the example, i'd say it never fires.

Cannot load data from .CSV file to Amcharts

I am new to javascript and am creating a piechart which loads data from a comma separated file data.txt but I cannot see anything in the browser when I open the html file.
data.txt consists the following data -
United States,9252
China,1882
Japan,1809
Germany,1322
United Kingdom,1122
India,984
My html code is-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>amCharts examples</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="amcharts/amcharts.js" type="text/javascript"></script>
<script type="text/javascript">
var chart;
var dataProvider;
window.onload = function() {
createChart();
loadCSV("data.csv");
}
// method which loads external data
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
// method which parses csv data
function parseCSV(data){
//replace UNIX new lines
data = data.replace (/\r\n/g, "\n");
//replace MAC new lines
data = data.replace (/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// create array which will hold our data:
dataProvider = [];
// loop through all rows
for (var i = 0; i < rows.length; i++){
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
// column is array now
// first item is date
var country = column[0];
// second item is value of the second column
var visits = column[1];
// third item is value of the fird column
// create object which contains all these items:
var dataObject = {country:country, visits:visits};
// add object to dataProvider array
dataProvider.push(dataObject);
}
}
// set data provider to the chart
chart.dataProvider = dataProvider;
// this will force chart to rebuild using new data
chart.validateData();
}
function createChart(){ // PIE CHART
chart = new AmCharts.AmPieChart();
// title of the chart
chart.addTitle("Visitors countries", 16);
chart.titleField = "country";
chart.valueField = "visits";
chart.sequencedAnimation = true;
chart.startEffect = "elastic";
chart.innerRadius = "30%";
chart.startDuration = 2;
chart.labelRadius = 15;
chart.pullOutEffect = "elastic";
chart.pullOutDuration = 1;
// the following two lines makes the chart 3D
chart.depth3D = 10;
chart.angle = 15;
// WRITE
chart.write("chartdiv");
}
</script>
</head>
<body>
<div id="chartdiv" style="width:600px; height:400px;"></div>
</body>
I have taken the code from http://blog.amcharts.com/2011/03/amcharts-javascript-tutorials-part-2.html and changed it according to piechart.
Please tell me what am I doing wrong.
I have placed data.txt in the same folder as the html file and have not hosted the file on a web server
You're calling loadCSV to load data.csv, but you said your data is in data.txt.
You should try to update your JS, Chrome throws this error : "AmCharts.AmPieChart is not a functioncreateChart # Pie Charts.html:75window.onload # Pie Charts.html:15"
Try to Use DATALOADER :
AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataLoader": {
"url": "data/pie.csv",
"format": "csv",
"delimiter": ",",
"useColumnNames": true
},

Categories

Resources