I want a highstocks chart that can plot multiple streams from CSV files. My csv data looks like:
TIMESTAMP,DATA
2013-07-25 17:52:13.490,98425702
2013-07-25 17:52:34.840,382307
2013-07-25 17:52:55.900,380769
2013-07-25 17:54:37.380,500000
2013-07-25 17:54:47.910,98360155
2013-07-25 17:54:58.440,430000
2013-07-25 17:55:08.970,282307
2013-07-26 19:46:30.950,116923
Javascript in my index.html:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/modules/data.js"></script>
<script type="text/javascript">
// Create the chart
$(function() {
var magx = [];
$.get('magx-11.csv', function(csv1) {
var lines = csv1.split('\n');
for (i=0; i<lines.length; i++) {
var elements = lines.split(',');
for (j=0; j<lines.length; j++) {
magx.push([ elements[j] ])
}
}
console.log(magx);
});
$('#container').highcharts('StockChart', {
xAxis: {
type: 'datetime'
},
title: {
text: 'Data'
},
series: [{
name: 'Mag X',
data: magx,
}]
});
});
</script>
With:
<body>
<div id="container" style="width: 1200px; height: 400px; margin: 0 auto"</div>
</body>
So, I'm trying first figure how I need to parse the data. I've seen various references on splitting for new line, and then on the ',' delimiter. But from logging output, I don't think the data is being passed into the next function that I would like some help with please.
This has little effect too:
magx.push([ parseFloat(elements[j])
I would like to be able to extend this for multiple csv files too.
(I'm ignoring the incorrect datetime handling there, for now).
I've already seen: Reading data from CSV with highstock and Highchart from CSV file with JavaScript. Many thanks in advance!
Trick was to investigate the JSON formats, then the Data.parse() formats. Documentation eh?
Also have "Highcharts error #15: http://www.highcharts.com/errors/15
highstock.js:13:195". My data is date-ordered, isn't that good enough?
Now need to convert this to multiple csv's per chart now.
$(function() {
var magx = [];
$.get('stuff.csv', function(csv1) {
var lines = csv1.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo > 0) {
var ds1 = items[0].split(' ');
magx.push( [ Date.parse(ds1[0] + "T" + ds1[1]) , parseFloat(items[1]) ] );
};
});
var options = {
xAxis: {
type: 'datetime'
},
exporting: {
enabled: true
},
series: [{
name: 'Data 1',
data: magx
}]
};
var chart = $('#container').highcharts('StockChart', options);
});
});
Related
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>
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.
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 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);
});
}
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);
});