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>
Related
I am getting some errors with this code. Apparently split is not a function. I am also getting this error:
GET http://localhost:8000/favicon.ico 404 (File not found)
Basically what I am trying to do is convert a csv to a 2D array through which I loop and do some analysis. I'm not great with javascript so please don't crucify me lol. But please feel free to point out any other issues I really need this to work!
<!DOCTYPE html>
<html>
<head>
<script src = "https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
d3.csv('enrollment.csv', function(data) {
function csvToArray(csv) {
rows = csv.split("\n");
return rows.map(function (row) {
return row.split(",");
});
};
let count = 0;
let enroll = csvToArray(data);
console.log(enroll);
let dup_Tracker = [];
for (i = 1; i < enroll.length; i++) {
if (enroll[i][1] === enroll[i-1][1]) {
if (enroll[i][0] !== enroll[i-1][0]) {
dup_Tracker.push(enroll[i]);
}
} else {
count += 1;
}
}
});
// console.log(dup_Tracker);
</script>
</body>
</html>
I'm trying to code a web-page that will display a pie-chart with results but the code for my pie-chart is in a HTML file (read_data.html) and the figures I would like to use for the pie-chart are in a JavaScript file (read_data.js)
The figures I want are stored in 4 variables - Booth1,Booth2,Booth3,Booth4
How could I go about transferring these variables to my HTML file?
Here is the code for the pie-chart in the HTML file
<!DOCTYPE html>
<html lang="en-US">
<body>
<h1>My Web Page</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Students', 'Votes'],
['Canidate1', Booth1],
['Canidate2', Booth2],
['Canidate3', Booth3],
['Canidate4', Booth4],
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'Election Results', 'width':550, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Here is the code in the JavaScript file
// Lists to hold the well being states and their corresponding times
var myVotes = [];
var myTimes = [];
// Variables to hold the count for each state
var Booth1 = 0;
var Booth2 = 0;
var Booth3 = 0;
var Booth4 = 0;
// Define database connection to correct child branch, ElectionResults
var myDBConn = firebase.database().ref("ElectionResults");
// Function that acts when a 'new child is added to the DB' - i.e. new data is added this function runs.
myDBConn.on("child_added", function(data, prevChildKey) {
Booth1 = 0;
Booth2 = 0;
Booth3 = 0;
Booth4 = 0;
// The data returned from the branch is put into a variable, dataPoint
var dataPoint = data.val();
// Populate the lists with the various data from the database
myVotes.push(dataPoint.ElectionResults);
myTimes.push(dataPoint.Time);
// Loop each returned state and add 1 to the appropriate counter
for (i = 0; i < myVotes.length; i++) {
if (myVotes[i] == "Canidate1") {
Booth1 = Booth1 + 1;
}
if (myVotes[i] == "Canidate2") {
Booth2 = Booth2 + 1;
}
if (myVotes[i] == "Canidate3") {
Booth3 = Booth3 + 1;
}
if (myVotes[i] == "Canidate4") {
Booth4 = Booth4 + 1;
}
}
// Update the page elements with the average and the last item (most rescent) off the list
document.getElementById("TimeID").innerHTML = myTimes[myTimes.length - 1];
// Update the page elements with the results of each count
document.getElementById("Booth1").innerHTML = Booth1;
document.getElementById("Booth2").innerHTML = Booth2;
document.getElementById("Booth3").innerHTML = Booth3;
document.getElementById("Booth4").innerHTML = Booth4;
});
I think that you can just include the JS file into the HTML file by useing the <script /> tag;
<script type="something" src="read_data.js"></script>
With this tag you inculded the file and can use the variables by opening another script tag;
<script>
//import variables here
</script>
I'm totally new in flot. At first I want to display three chart(d1, d2, d3) data in the same page and after that when I click on new chart button first chart(d1) will hide and new chart(d4) will insert and three chart(d2,d3,d4) will show and continuing the process. But the problem is that graph is not displaying. If I use random data under a function then it is showing the graph like this but when I tried with different variables, the graph is not showing.
How can I fix this problem?
Here is my code:
<html>
<head>
<title>Graph</title>
<style>
div.placeholder {
width: 400px;
height: 200px;
}
</style>
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="jquery.flot.js"></script>
<script type="text/javascript">
function getdata(){
var d1 = [[0,1],[1,4],[2,4],[3,8],[4,2],[5,11],[6,19]];
var d2 = [[7,1],[8,5],[9,4],[10,13],[11,2],[12,11],[13,19]];
var d3 = [[14,10],[15,4],[16,14],[17,8],[18,2],[19,1],[20,19]];
var d4 = [[21,4],[22,11],[23,18],[24,12],[25,1],[26,19],[27,8]];
var d5 = [[28,5],[29,14],[30,13],[31,2],[32,11],[33,9]];
}
$(document).ready(function () {
getdata();
var dataset1 = [{
label: "Day1",
data: d1,
points: { symbol: "triangle" }
}];
var dataset2 = [{
label: "Day2",
data: d2,
points: { symbol: "cross" }
}];
var dataset3 = [{
label: "Day3",
data: d3,
points: { symbol: "square" }
}];
var dataset4 = [{
label: "Day4",
data: d4,
points: { symbol: "diamond" }
}];
var dataset5 = [{
label: "Day5",
data: d5,
points: { symbol: "circle", color: "black" }
}];
for(var i = 1, j = 0; i < dataset.length, j < $('div.placeholder').length; i++, j++){
$.plot("div.placeholder:eq("+j+")"),[dataset("+i+")];
}
function update() {
$('div.placeholder:visible:first').hide();
$('div.placeholder:last').after($('<div>').addClass('placeholder'));
$.plot("div.placeholder:last", [getdata()]);
}
$('#btn').on('click', update);
});
</script>
</head>
<body>
DAY 1<div class="placeholder"></div>
DAY 2<div class="placeholder"></div>
DAY 3<div class="placeholder"></div>
<input id="btn" type="button" value=" New Chart " />
</body>
</html>
There are multiple of issues with your code, most of which are not specific to Flot:
The d1... arrays are local to the getdata() function and not defined outside of it where you try to use them
You use dataset in your for loop like an array, but there is not such variable defined
Your call of the plot() method makes no sense, you can't access variables like this: $.plot("div.placeholder:eq(" + j + ")"), [dataset("+i+")];
The call to plot() in the update() function tries to use the raw data, not you labeled data (but fails because of point 1 above).
Here is a fiddle with most of the issues fixed. It still does not handle the titles above the charts when updating and gives errors after updating more then two times (when your data is used up).
I am reading in and looping through a json file to create a graph with nodes and edges using a JavaScript library cytoscape, but am having some newbie problems. Here is my pseudo code w/pseudo bugs.
1) Create new node for each node with label 'x'
2) For each edge in edges, create edge with 'source', 'target'.
The problem that I am having is that to create the edge I need to pass each node object as the argument, (sourceNode, targetNode, {weight: 'y'} so something like this will not work
var edge = graph.newEdge({source: graphP.elements.edges[j].data.source},
{target: graphP.elements.edges[j].data.target});
I tried creating an array and writing each new node to it, but I just end up over-writing the value of the variable name and end up with an array of length 1. While all my nodes are created, I need a way to go back and access the nodes in order to create the edges ( and obviously not have them point to themselves).
I am guessing it will be some sort of nodeObject.hasKey[label] and match on that label to retrieve node ID, then create new edge?
I've thought myself in a knot here. Any advice is appreciated. Below is my current code with abbreviated json file read in.
<html>
<head>
<title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>-->
<script/>
$(document).ready(function(){
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/SuperSmallNodes.json',
type: 'GET',
dataType: 'json'
}).done(function(graphP) {
console.log(graphP);
var graph = new Springy.Graph();
for ( i = 0 ; i < graphP.elements.nodes.length ; i++ ) {
var nodeArray = []
var Nlabel1 = graphP.elements.nodes[i].data.label
var Nlabel2 = graphP.elements.nodes[i++].data.label
console.log('Nlabel1')
console.log(Nlabel1)
console.log('Nlabel2')
console.log(Nlabel2)
var NN1 = graph.newNode({label: Nlabel1})
var NN2 = graph.newNode({label: Nlabel2})
nodeArray.push(NN1)
nodeArray.push(NN2)
graph.newEdge(NN1,NN2, {weight: .5})
}
console.log('NODE ARRAY')
console.log(nodeArray)
console.log('WINDOW')
jQuery(function(){
var springy = window.springy = jQuery('#springydemo').springy({
graph: graph,
nodeSelected: function(node){
console.log('Node selected: ' + JSON.stringify(node.data));
}
});
});
});
});
</script>
<div>
<canvas id="springydemo" width="800" height="400" style="border: 1px solid black;"></canvas>
</div>
</body>
</html>
At minimum, I would think you'd want to initialize nodeArray outside of the loop:
var nodeArray = []
for ( i = 0 ; i < graphP.elements.nodes.length ; i++ ) {
As is, the re-initialization in each loop would explain the length of 1.
I apparently got so focused on other problems that I didn't see that I was initializing my array inside the loop. Genius. However, for reference, here is how I was able to pass the sourceNode and targetNode objects to the newEdge function.
<html>
<head>
<title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>-->
<script/>
$(document).ready(function(){
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/SuperSmallNodes.json',
type: 'GET',
dataType: 'json'
}).done(function(graphP) {
console.log(graphP);
var graph = new Springy.Graph();
var nodeArray = []
for ( i = 0 ; i < graphP.elements.nodes.length ; i++ ) {
var Nlabel1 = graphP.elements.nodes[i].data.label
var Nmass = graphP.elements.nodes[i].data.mass
var NN1 = graph.newNode({label: Nlabel1}, {'text-outline-width': Nmass});
nodeArray.push(NN1)
}
console.log(nodeArray)
function getByValue(arr, value) {
for (var n=0; n < nodeArray.length; n++) {
if (arr[n].data.label == value) {
console.log("below should be the object of element")
return arr[n];
}
}
}
function getSourceNode(graphP) {
for (var s=0; s < graphP.elements.edges.length; s++) {
var getSource = graphP.elements.edges[s].data.source
var getTarget = graphP.elements.edges[s].data.target
graph.newEdge(getByValue(nodeArray, getSource),getByValue(nodeArray, getTarget));
}
}
getSourceNode(graphP)
console.log('WINDOW')
jQuery(function(){
var springy = window.springy = jQuery('#springydemo').springy({
graph: graph,
nodeSelected: function(node){
console.log('Node selected: ' + JSON.stringify(node.data));
}
});
});
});
});
</script>
<div>
<canvas id="springydemo" width="800" height="400" style="border: 1px solid black;"></canvas>
</div>
</body>
</html>
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);
});
}