Displaying data points from server side txt file on google graph - javascript

I would like to display my retrieved data points from my server side text file
on a google graph. During research i can now retrieve the data from my temps.txt
file using $.get().
I just started learning javascript , so this may be something obvious that i missed.
I can also display a sample google graph with some example datapoints.
How can i put the two together? , below i have both source files
from my attempts so far.
Getting the Datapoints:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
$.get('temps.txt', function(data) {
times = data.split("\n");
var html = [];
for (var i in times) {
html.push(times[i] + '<br/>');
}
html.push( times[0] * 3 );
$('body').append(html.join(''));
});
</script>
</html>
Showing the GRAPH:
<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 data = google.visualization.arrayToDataTable([
['Hours', 'Temperature'],
['18:00', 20.7],
['19:00', 21],
['20:00', 22.3],
['20:30', 22.5],
['21:00', 22.0],
['22:00', 21.6]
]);
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 700px; height: 400px;"></div>
</body>
</html>
Temps.txt file is a simple text file with one measured value every hour
the first line is 00:00 hrs the 2nd line 01:00 hrs and so on see below:
15.3
16.4
16.7
18.8
... etc

Well, would be something like this:
function drawChart() {
$.get('temps.txt', function(txt) {
vals = txt.split("\n");
var hour= 0;
var dataArr=[['Hours', 'Temperature']]
for(var i = 0; i < vals.length;i++){ // build data array
//add the hour in 'hh:00' format and the temperature value
dataArr.push([('0'+hour).substring(-2)+':00', parseFloat(vals[i])]);
hour+=1;
}
var data = google.visualization.arrayToDataTable(dataArr)
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}

Related

Plotly js live update from online data

I would like my Plotly graph to update automatically every 1 seconds by reading data from an online CSV file.
This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="graph"></div>
<script>
function read_data() {
d3.csv(
"https://docs.google.com/spreadsheets/d/e/2PACX-1vTkbRgvvBwM0tMheEziQC4ldtYoMVCgIek67Y5Lcjnu1WH0tTLLCzJPse-pL5OTR9U58Gk8VBD65L3u/pub?gid=0&single=true&output=csv",
function (data) {
processData(data);
}
);
}
function processData(allRows) {
console.log(allRows);
var x = [];
var y = [];
for (var i = 0; i < allRows.length; i++) {
row = allRows[i];
x.push(row["x"]);
y.push(row["y"]);
}
console.log("Y", y);
return y;
}
Plotly.newPlot(graph, [
{
y: [1, 2, 3],
mode: "lines",
line: { color: "#80CAF6" },
},
]);
var interval = setInterval(function () {
Plotly.restyle(
graph,
{
y: [[read_data()]],
},
[0]
);
}, 1000);
</script>
</body>
</html>
Although the y data is printed in the console, the plot is not updated.
My script is based on these two tutorials:
Streaming in JavaScript
Read CSV Data from an Ajax Call in JavaScript
Additional question: is there a way to automatically update the graph each time the data is updated in the CSV document? That is, without having to loop over each second.
In your code, read_data() returns undefined. It also schedules processData() to run later, and that function returns some data, but it was called by the JavaScript runtime which ignores this returned value.
You could stick the Plotly.restyle(... code in a function that processData calls, or you could stick that code inside processData. See the code sample below.
However, there's another issue here (watch the code sample below fail). This file can't be loaded by a browser page right now. Google sheets links like
https://docs.google.com/spreadsheets/d/e/2PACX-1vTkbRgvvBwM0tMheEziQC4ldtYoMVCgIek67Y5Lcjnu1WH0tTLLCzJPse-pL5OTR9U58Gk8VBD65L3u/pub?gid=0&single=true&output=csv no longer work in the browser as of about 18 months ago.
You'll need to use another method to get your data into a web page (see linked questions above for some suggestions).
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="graph"></div>
<script>
function read_data() {
d3.csv(
"https://docs.google.com/spreadsheets/d/e/2PACX-1vTkbRgvvBwM0tMheEziQC4ldtYoMVCgIek67Y5Lcjnu1WH0tTLLCzJPse-pL5OTR9U58Gk8VBD65L3u/pub?gid=0&single=true&output=csv",
function (data) {
processData(data);
}
);
}
function processData(allRows) {
console.log(allRows);
var x = [];
var y = [];
for (var i = 0; i < allRows.length; i++) {
row = allRows[i];
x.push(row["x"]);
y.push(row["y"]);
}
console.log("Y", y);
Plotly.restyle(
graph,
{
y: y,
},
[0]
);
}
Plotly.newPlot(graph, [
{
y: [1, 2, 3],
mode: "lines",
line: { color: "#80CAF6" },
},
]);
var interval = setInterval(read_data, 1000);
</script>
</body>
</html>

groupByRowLabel doesn't work on Google Timeline

Currently, My timeline Chart looks like this
but I want to put all bars which is the same country on one row
and I already set
timeline:{groupByRowLabel:true}
in options but it doesn't work
My data from google sheet looks like this
My full code below
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>
<script>
google.charts.load('current', {
packages: ["timeline"]
});
google.charts.setOnLoadCallback(drawRegionsMap);
var data1;
function handleQueryResponseTR1(response1) {
if (response1.isError()) {
alert('Error in query: ' + response1.getMessage() + ' ' + response1.getDetailedMessage());
return;
}
data1 = response1.getDataTable();
var view1 = new google.visualization.DataView(data1);
view1.setColumns([{
type: 'string',
id: 'Country',
calc: function(dt, row) {
return dt.getFormattedValue(row, 0)
}
}, 1, 3, 4]);
var chart1 = new google.visualization.Timeline(document.getElementById('colormap1'));
var options1 = {
width: 800,
height: 1600,
timeline: {
groupByRowLabel: true
}
}
chart1.draw(view1, options1);
}
function drawRegionsMap() {
var query1 = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1sOyYwL51uWTd7Pv4Sp_bKdxWmH-g6QA2SDHhw93_2s8/edit?usp=sharing");
query1.send(handleQueryResponseTR1);
}
</script>
<div id='colormap1'> </div>
What you have done is absolutely correct. there is nothing to be added in your code.
timeline:{groupByRowLabel:true}
this will give your labels in same row.
But the problem here is the dataset that ur giving.
All the labels for country(in ur case) will come in same row if and only if date of labels are not overlapping.
say for example, in ur case.
Albania WEEE 7/20/2000 6/6/2017
Albania Batteries 7/20/2015 6/5/2017
See the above dates (end time of WEEE and start time of Batteries) are overlapiing.
if the dates are like
Albania WEEE 7/20/2000 6/6/2016
Albania Batteries 6/6/2016 6/5/2017
check this dates. with this data set ur labels will come in the same row.

How to draw google barchart using dynamic data from Json

I am trying to get Json data using the $.getJSON() method.
And this is the result:
Hcount:29Acount:0Pcount:12Ccount:0
I wanted to draw a bar chart using the result count with the help of the google chart API so I used the getbar() method. But nothing happenes after passing the getbar() method.
Here is the Javascript and HTML code:
function getStats() {
var obj1="";
$.getJSON('getbusinessstats', function(response) {
var txnSource = "";
$.each(response.tanSource, function(key, value) {
tanSource += key+":"+value
});
obj1={ "Array1": [tanSource] };
alert(obj1.Array1)
getbar(obj1);
//$('#vis_div tbody').html(tanSource);
});
}
function getbar(obj2)
{
google.load('visualization', '1');
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [obj2],
options: {'title': 'INPUT'},
containerId: 'vis_div'
});
wrapper.draw();
}
}
$(document).ready(function() {
getStats();
setInterval(function() {
getStats();
}, 5000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="lib/jquery-1.11.1.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<div >
<span class="label label-info">INPUT </span>
<table id="vis_div">
<tbody>
</tbody>
</table>
</div>
</body>
</html>

how to access sqlite3 database table values from javascript?

My task is to report a graph by accessing sqlite3 database table values. So i created database in python and i used javascript to report a graph.In python, i fetched all values from database and stored in list. Now, my problem is i dono how to access python list values from javascript. please help me..
import sqlite3
list = []
conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")
for row in cursor:
print "date :", row[0]
print "gb :", row[1]
list.append([row[0],row[1]])
def memory():
return list
req = memory();
print req #This is the list which i created
memory();
ff = open('chart.html','w')
msg='''
<html>
<head>
<script type="text/javascript"
src=\'https://www.google.com/jsapi?autoload={
"modules":[{
"name":"visualization",
"version":"1",
"packages":["corechart"]
}]
}\'></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ .
#i want to pass that list variable here...help please..
]);
var options = {
title: "PERSISTENT AUTOMATION MEMORY USAGE REPORT",
curveType: "function",
legend: { position: "bottom" }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>'''
ff.write(msg)
ff.close()
import sqlite3
from string import Template
conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")
results = []
for row in cursor:
results.append({'date': row[0], 'gb': row[1]})
print "date :", row[0]
print "gb :", row[1]
template = '''
<html>
<head>
<script type="text/javascript"
src=\'https://www.google.com/jsapi?autoload={
"modules":[{
"name":"visualization",
"version":"1",
"packages":["corechart"]
}]
}\'></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Memory", "Usage (GB)"],
$res
]);
var options = {
title: "PERSISTENT AUTOMATION MEMORY USAGE REPORT",
curveType: "function",
legend: { position: "bottom" }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>'''
with open('chart.html', 'w') as html:
data = ','.join(['["{date}", {gb}]'.format(**r) for r in results])
html.write(Template(template).substitute(res=data))
You should iterate over list and concatenate items to the result string.
items = ['apple', 'grape']
html_string = '''
<html> <body> <h1> My list </h1> <ul>{list}</ul> </body> </html>
'''
my_list = ''.join(['<li>{}</li>'.format(i) for i items])
html_string = html_string.format(list=my_list)
with open('test.html', 'w') as html:
html.write(html_string)
This is a very easy way to achieve the above task.
import ast
memory_used = "/Users/Shared/MemoryUsed.log"
memory_used = []
with open(memory_used) as f:
for line in f:
linesplit = line.split()
date = linesplit[1]
gbsplit = linesplit[2]
gb = ast.literal_eval(gbsplit[0])
memory_used.append([date,gb])
print memory_used #This is the list
ff = open('chart_new_try.html','w')
html1="""<html>
<head>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'MemoryUsed'],"""
html2 = """ ]);
var options = {
title: 'GRAPH REPORT',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>"""
msg = html1 + memory_used + html2
ff.write(msg)
ff.close()

HighCharts reading from CSV basic example

Am new to highcharts and JS and am trying to plot data from a csv file (data3.csv).
Here is the code at the moment:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../js/excanvas.compiled.js"></script>
<![endif]-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Stock Chart'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Price'
}
},
series: []
};
$.get('data3.csv', function(data) {
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
And the contents of the csv file are:
Date Open
29/01/2010 538.49
28/01/2010 544.49
27/01/2010 541.27
26/01/2010 537.97
25/01/2010 546.59
However, this is not giving a chart (just gives the title).
Could anyone suggest where I am going wrong?
Thanks
In line
var items = line.split(',');
You should spline csv by commas, but you have space. So you can replace this line with:
var items = line.split(' ');
or generate csv which items will separated by comma.
As a result your parser should looks like:
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo>0)
{
options.xAxis.categories.push(items[0]); //set first column from CSV as categorie
options.series[0].data.push(parseFloat(items[1])); //set second column from CSV as point value
}
});
// Create the chart
var chart = new Highcharts.Chart(options);
});

Categories

Resources