HighCharts reading from CSV basic example - javascript

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);
});

Related

How to display column headers in Y axis for a Datatable using HighCharts?

I am using Datatables and HighCharts. Please see my code below. I am not sure how to display this bar chart where Years are displayed in Y axis. I have added an image below to show how it looks like.
I am new to HighCharts, so I am not sure of all the functions. Thanks.
How can I get graph to show like this? I want years in Y axis. Thanks.
http://live.datatables.net/febayaxa/1/edit
$(document).ready(function() {
var table = $("#example1").DataTable();
var salary = getSalaries(table);
// Declare axis for the column graph
var axis = {
id: "salary",
min: 0,
title: {
text: "Number"
}
};
// Declare inital series with the values from the getSalaries function
var series = {
name: "Overall",
data: Object.values(salary)
};
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series]
});
// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});
function getSalaries(table) {
var salaryCounts = {};
var salary = {};
// Get the row indexes for the rows displayed under the current search
var indexes = table
.rows({ search: "applied" })
.indexes()
.toArray();
// For each row, extract the office and add the salary to the array
for (var i = 0; i < indexes.length; i++) {
var office = table.cell(indexes[i], 0).data();
if (salaryCounts[office] === undefined) {
salaryCounts[office] = [+table.cell(indexes[i], 1).data().replace(/[^0-9.]/g, "")];
}
else {
salaryCounts[office].push(+table.cell(indexes[i], 1).data().replace(/[^0-9.]/g, ""));
}
}
// Extract the office names that are present in the table
var keys = Object.keys(salaryCounts);
// For each office work out the average salary
for (var i = 0; i < keys.length; i++) {
var length = salaryCounts[keys[i]].length;
var total = salaryCounts[keys[i]].reduce((a, b) => a + b, 0);
salary[keys[i]] = total / length;
}
return salary;
};
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example1" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
<tr ><td> Data</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr></tbody>
</tbody></table>
I am going to assume you mean the x-axis (the horizontal axis) when you say that you want to use the years (from the table headings) from your DataTable for each bar's label in the chart.
You can access these table headings using the DataTables API and some jQuery.
Use this to get an array of table heading elements:
api.columns().header()
And then use $(element).html() to get the label (the year) from each heading.
There is a lot of code in your example in the question which does not appear to be relevant to the chart you want to create, so in the following example, I removed all of that. If it is needed, you can put it back.
$(document).ready(function() {
var tableData = [];
var tableCategories = []
var table = $("#example1").DataTable({
initComplete: function(settings, json) {
let api = new $.fn.dataTable.Api(settings);
// get the seris data as an array of numbers from the table row data:
api.rows().data().toArray()[0].forEach(function(element, index) {
if (index > 0) {
tableData.push(parseFloat(element.replace(/,/g, '')));
}
});
// get the x-axis caregories from the table headings:
api.columns().header().toArray().forEach(function(element, index) {
if (index > 0) {
tableCategories.push($(element).html());
}
});
  
}
});
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: tableCategories
},
series: [{
data: tableData
}]
});
});
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example1" class="display nowrap" width="100%">
<thead>
<tr>
<th>Year</th>
<th>2012</th>
<th>2013</th>
<th>2014</th>
<th>2015</th>
<th>2016</th>
<th>2017</th>
<th>2018</th>
<th>2019</th>
<th>2020</th>
<th>2021</th>
</tr>
</thead>
<tr>
<td> Data</td>
<td>3,823</td>
<td>3,823</td>
<td>3,954</td>
<td>3,959</td>
<td>3,955</td>
<td>3,956</td>
<td>3,843</td>
<td>3,699</td>
<td>3,472</td>
<td>3,551</td>
</tr>
</tbody>
</tbody>
</table>
The output looks like this:
If you do actually want the years labels to be displayed on the y-axis (with horizontal bars, instead of vertical bars) then you can change the chart type by changing this part of the chart...
chart: { type: "column" },
to this:
chart: { type: "bar" },

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>

Highcharts/highstocks Javascript from CSV file

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);
});
});

Displaying data points from server side txt file on google graph

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);
});
}

Categories

Resources