I'm plotting Csv column data in highcharts. Instead of the:
$.get('5.csv', function(data)
I want input a local desktop Csv file using:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
My current Javascript code is below :
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
title: {
text: 'Test'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units',
}
},
series: []
};
// $.get('5.csv', function(data) {
var file = event.target.file;
var reader = new FileReader();
var txt=reader.readAsText(file);
var lines = txt.split('\n');
var c = [], d = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
c = [parseFloat(items[0]), parseFloat(items[1])];
d.push(c);
console.log(c);
}
});
options.xAxis.categories = c;
options.series = [{
data: d
}];
chart = new Highcharts.Chart(options);
});
How would I go about doing this ? I want to upload a Csv file from a local desktop machine. How do I link the File Reader upload of the file to highcharts to plot, instead of using the $.get(5.csv', function(data) { ? Or am I better using jquery-csv (https://github.com/evanplaice/jquery-csv). I know there are browser security issues. My file is a 3 column Csv with a one line header, column 1 is the x-axis, 2 is the y-axis, 3 will be the error bar, which I haven't yet implemented:
Q,I,E
0.009,2.40E-01,5.67E-02
0.011,2.13E-01,3.83E-02
0.013,2.82E-01,2.28E-02
etc ....
This works now upload by File API
function processFiles(files) {
var chart;
options = {
chart: {
zoomType: 'x',
renderTo: 'container',
type: 'line',
zoomType: 'x'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'Q'}
},
yAxis: {
type: 'linear',
minorTickInterval: 0.1,
title: {
text: 'I(ntensity)'
},
},
tooltip: {
shared: true
},
legend: {
enabled: true
},
plotOptions: {
area: {
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, Highcharts.getOptions().colors[0]],
[0, 'rgba(2,0,0,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
series: [{
name: 'Series'}]
};
var file = files[0]
var reader = new FileReader();
reader.onload = function (e) {
str = e.target.result;
var lines = str.split("\n");
var c = [], d = [], er = [];
$.each(lines, function(lineNo, line) {
if(lineNo > 0 ){
var items = line.split(',');
var strTemp = items[0];
er = parseFloat(items[2])
a = parseFloat(items[0])
b = parseFloat(items[1])
min = (b - (er/2))
max = b + ((er/2))
c = [a , b];
var q = [], e = [];
q = [min, max]
e.push(q);
d.push(c);
console.log(c);
console.log(q);
}
});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d,
type: 'scatter'
}, {
name: 'standard deviation',
type: 'errorbar',
color: 'black',
data : e }
];
$("#Linear").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'linear'});
});
$("#Log").click(function(){
$('#container').highcharts().yAxis[0].update({ type: 'logarithmic'});
});
$("#Guinier").click(function(){
$('#container').highcharts().yAxis[0].update({ data: Math.log(d)});
options.xAxis.categories = c.name;
lineWidth: 1
options.series = [{
data: d
}]
});
chart = new Highcharts.Chart(options);
}
reader.readAsText(file)
var output = document.getElementById("fileOutput")
};
Due to security reasons you can't load a file directly on the client-side
To do this you need to use the HTML5 File API which will give the user a file dialog to select the file.
If you plan to use jquery-csv here's an example that demonstrates how to do that.
File Handling Demo
I'm biased but I say use jquery-csv to parse the data, trying to write a CSV parser comes with a lot of nasty edge cases.
Source: I'm the author of jquery-csv
As an alternative, if jquery-csv doesn't meet your needs, PapaParse is very good too.
Related
Got a column called ChartData in database with a string value of 4,11,25,36,50. Trying to assign this value to a hidden variable so JS can read the value of this and put this value in the data option using high charts. I have console.log the variable and looks like its appearing as a string rather than an array when being parsed across the server side to the client side.
C# code
string str = reader["ChartData"].ToString();
string[] strList = str.Split(','); //seperate the hobbies by comma
// convert it in json
dataStr = JsonConvert.SerializeObject(strList, Formatting.None);
hiddenvariable.Value = dataStr;
JS code:
function CreateBoxPlot() {
var hv = $('#hiddenvariable').val();
alert(hv); //["40","61","65","74","77"]
var chart;
var titleText = 'Test Chart Title';
var subTitleText = 'Test Chart Subtitle';
var type = 'boxplot';
var data = hv;
console.log(data); //["40","61","65","74","77"]
$(function () {
$('#container').highcharts({
chart: { type: type, inverted: true },
title: { text: titleText },
subtitle: { text: subTitleText },
legend: { enabled: false },
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({ data: data });
});
}
However when i hardcode data to the below value this works. How do i format this correctly when its parsed over to the JS side:
var data = [[40,61,65,74,77]]
You have to convert the string '["40","61","65","74","77"]' to js array with numbers. To make it work on each browser you can follow this approach:
Parse the string to js array using JSON.parse()
Loop through the created array and convert each element to number:
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
Code:
$(function() {
var json = '["40","61","65","74","77"]',
dataString = JSON.parse(json),
data = [],
i;
for (i = 0; i < dataString.length; i++) {
data[i] = +dataString[i];
}
$('#container').highcharts({
chart: {
inverted: true
},
legend: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
pointWidth: 50
}
},
xAxis: {
visible: false
},
yAxis: {
visible: true,
title: {
text: 'Values'
},
plotLines: [{
value: 80,
color: 'red',
width: 2
}]
}
});
chart = $('#container').highcharts();
chart.addSeries({
data: data
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
Demo:
https://jsfiddle.net/BlackLabel/ay1xmgoc/
Taking reference from the comments, add this to your code and then try.
var data = hv.map(function (element) {
return +element;
});
I tried the code like this with many small restructuration and modification but without success.
Here is the code:
$(function () {
$.get('data.csv', function(data) {
// split the data set into ohlc and volume
var ohlc = [],
volume = [],
dataLength = data.length,
// set the allowed units for data grouping
groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]],
i = 0;
for (i; i < dataLength; i += 1) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
volume.push([
data[i][0], // the date
data[i][5] // the volume
]);
}
$('#chart').highcharts({
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Historical'
},
yAxis: [{
labels: {
align: 'right',
x: -3
},
title: {
text: 'OHLC'
},
height: '60%',
lineWidth: 2
}, {
labels: {
align: 'right',
x: -3
},
title: {
text: 'Volume'
},
top: '65%',
height: '35%',
offset: 0,
lineWidth: 2
}],
data: {
csv: data
},
series: [{
type: 'candlestick',
name: 'AAPL',
data: ohlc,
dataGrouping: {
units: groupingUnits
}
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
dataGrouping: {
units: groupingUnits
}
}]
});
});
});
Here is data.csv:
Date,Open,High,Low,Close,Volume
2013-12-20,9371.08,9413.09,9352.98,9400.18,161686900
2013-12-19,9279.68,9351.9,9257.24,9335.74,98276500
2013-12-18,9145.35,9190.73,9122.05,9181.75,82342700
2013-12-17,9142.75,9161.8,9085.12,9085.12,72207500
2013-12-16,9004.62,9187.78,8997.75,9163.56,99105600
2013-12-13,9016.78,9046.63,8990.58,9006.46,67761700
2013-12-12,9032.67,9060.54,8984.28,9017,75120200
2013-12-11,9093.26,9153.14,9065.51,9077.11,64845800
2013-12-10,9180.29,9223.73,9091.97,9114.44,74363400
Can you help me to figure out the problem or purpose new approch please ?
What is my goal ?
Is to be able to load a CSV file inside the chart instead of using JSON file.
Why ?
Because modifing CSV file is more easier for me using PHP than JSON, and it's for performance too.
Thank's
When you do data.length, you are getting length of the csv file string. What you need to do is split the data with the newline delimiter.
// sample from data
var data = `Date,Open,High,Low,Close,Volume
2013-12-20,9371.08,9413.09,9352.98,9400.18,161686900
2013-12-19,9279.68,9351.9,9257.24,9335.74,98276500`;
// split by \n (new line)
data = data.split('\n'); // now data is an array of rows
var finalObj = [];
// iterate over the rows
data.map(function(row){
var obj = {};
// row is a string separated by ','
row = row.split(','); // now row is an array
obj['date'] = row[0];
obj['open'] = row[1];
obj['high'] = row[2];
obj['low'] = row[3];
obj['close'] = row[4];
obj['volume'] = row[5];
finalObj.push(obj);
})
console.log(finalObj);
Output:
[
{
date:'Date',
open:'Open',
high:'High',
low:'Low',
close:'Close',
volume:'Volume'
},
{
date:'2013-12-20',
open:'9371.08',
high:'9413.09',
low:'9352.98',
close:'9400.18',
volume:'161686900'
},
{
date:'2013-12-19',
open:'9279.68',
high:'9351.9',
low:'9257.24',
close:'9335.74',
volume:'98276500'
}
]
I am trying to dynamically load in a number of series, depending on projects chosen by the user. I am using Laravel 5.2, PHP 5.6 and HighCharts.
I have managed to load in one JSON file, which is generated when the user selects projects. But I would like it if the JavaScript could parse the different series from the JSON file and dynamically load this into the series.
This is the code which I am using:
$(function () {
// Set up the chart
var processed_json = new Array();
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
name: 'Grades',
data: processed_json
}],
credits: {
enabled: false
}
});
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
});
My JSON is formatted like:
[{"key":"Math","value":6},{"key":"Biology","value":"8"},{"key":"English","value":"7"},{"key":"Gym","value":"4"}]
So I would like to have more JSONs like so, in one file to be parsed in the Javascript and be loaded in into the series.
Thank you!
EDIT
thanks for your reply. I have edited my code:
$(function () {
var processed_json = new Array();
var options = {
chart: {
renderTo: 'container',
type: 'column',
options3d: {
enabled: true,
alpha: 0,
beta: 0,
depth: 0,
viewDistance: 25
}
},
title: {
text: 'Grades'
},
subtitle: {
text: 'Dataset'
},
plotOptions: {
column: {
depth: 0
}
},
series: [{
}],
credits: {
enabled: false
}
};
$.getJSON('/uploads/test.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].key, data[i].value]);
}
});
options.series[0].remove();
options.series[0].setData = {
name: 'Grades',
data: processed_json
}
var chart = new Highcharts.Chart(options);
chart.redraw(true);
function showValues() {
$('#alpha-value').html(chart.options.chart.options3d.alpha);
$('#beta-value').html(chart.options.chart.options3d.beta);
$('#depth-value').html(chart.options.chart.options3d.depth);
}
// Activate the sliders
$('#sliders input').on('input change', function () {
chart.options.chart.options3d[this.id] = this.value;
showValues();
chart.redraw(false);
});
showValues();
});
But nothing is displayed anymore and the following error is given
TypeError: options.series[0].remove is not a function
I have also tried
var chart = new Highcharts.Chart(options);
chart.series[0].remove();
chart.series[0].setData = {
name: 'Grades',
data: processed_json
}
chart.redraw(true);
But this gives:
TypeError: Cannot set property 'setData' of undefined
I think highcharts has a method chart.addSeries for adding a new series. If you want to replace the current series with a new series, you can try removing first the current series using chart.series[0].remove( ) then add the new series with chart.addSeries. The parameter for the chart.addSeries can be an object like your
{
name: 'Grades',
data: processed_json
}
Then, define method with load data.. example:
function(chart) {
$.each(chart.series, function(i, v){
chart.series[i].remove(true);
});
chart.addSeries({your_data}, true);
}
check http://api.highcharts.com/highcharts/Chart.addSeries/Chart.addSeries
In my webapp, i use 10 of 15 types of graphs highchart and all dynamically load and work fine :) Highcharts is awesome.
I'm struggling to solve a problem I have with getting a chart to be redrawn after navigating to another view and then return back to the same chart view.
I'm using Backbone.js and Underscore as a MVC and templating solution for my application.
When I navigate to the charting page initially it works great, but if I move away and then come back I get a `TypeError: chart.series[0] is undefined in the console log.
I have highlighted line where the error occurs in the code below, close to the end.
My thought is that I may need to destroy() the chart at some point, but I'm unsure where I would do this and if it would solve my problem.
I recently changed the script to now use HighStock 'Highstock JS v1.3.6 (2013-10-04)' from earlier HighCharts ver 2.3.5, where it appeared that I did not have this issue.
The app is live online if anyone really needs or wants to see it in action, let me know.
The following code section is the function thatis called by the Backbone router.
If there is a need for other sections of code, please let me know.
I'll be grateful for any advice.
EDIT:
I have managed to get this in JSFiddle for anyone to view the problem.
Clickty clack your fury tailless one here http://jsfiddle.net/rockwallaby/pqKWj
When you first run it up, you will get a trend being displayed.
Then hit the 'Go to a different page' link, you will get a fairly blank page.
On that page there is a link to bring you back to the trend page.
Hitting that link brings you back but the trend does not get rendered correctly due to the above mentioned error.
//=================================================================================
// trendsBattery
// A simple trend view showing Battery Volts and Solar Charge
//
window.trendsBattery = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendsTemplate),
chart: null,
chartoptions:{
chart: {
renderTo: 'chart-container',
},
rangeSelector: {
enabled: false,
},
title:{
text:'Battery Volts & Solar Amps'
},
xAxis: {
type:'datetime',
dateTimeLabelFormats: {month:'%e. %b',year:'%b'}
},
yAxis: [{
title :{text: 'Battery Volts'},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0',
},
{
title :{text: 'Solar Charge Amps'},
min: 0,
max: 16,
opposite: true,
},
],
series:[
{yAxis: 0, data: [], type: 'line', step: true, name: 'Battery Vdc'},
{yAxis: 1, data: [], type: 'line', step: true, name: 'Solar Amps'},
],
},
render:function() {
that = this;
$(this.el).html(this.template());
this.chartoptions.chart.width = (windowWidth);
this.chartoptions.chart.height = (windowHeight - 150);
setTimeout(function() {
chart = new Highcharts.StockChart(that.chartoptions);
chart.events ={load: that.requestData(this.chart) };
},20);
return this;
},
requestData: function(chart){
var querystring = '//myHostServer.com/myFolder/myPHP.php';
jQuery.get(querystring, null, function(csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
};
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0]) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
};
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
},
});
I just updated jsfiddle with the suggestion I provided in comment, it's working.
window.trendView = Backbone.View.extend({
trendModel: new TrendsModel(),
template: _.template(trendTemplate),
chart: null,
getChartOptions: function () {
return {
chart: {
animation: true,
renderTo: 'chart-container',
backgroundColor: '#fff'
},
rangeSelector: {
enabled: false
},
title: {
text: 'Battery Volts & Solar Amps'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e. %b',
year: '%b'
} // don't display the dummy year:
},
yAxis: [{
title: {
text: 'Battery Volts'
},
min: 22,
max: 32,
minorGridLineColor: '#E0E0E0'
}, {
title: {
text: 'Solar Charge Amps'
},
min: 0,
max: 16,
opposite: true
}],
series: [{
yAxis: 0,
data: [],
type: 'line',
step: true,
name: 'Battery Vdc'
}, {
yAxis: 1,
data: [],
type: 'line',
step: true,
name: 'Solar Amps'
}]
}
},
render: function () {
that = this;
$(this.el).html(this.template());
var chartOptions = that.getChartOptions();
chartOptions.chart.width = (windowWidth - 50);
chartOptions.chart.height = (windowHeight - 50);
setTimeout(function () {
chart = new Highcharts.StockChart(chartOptions);
chart.events = {
load: that.requestData(this.chart)
};
}, 20);
return this;
},
requestData: function (chart) {
var querystring = '//paulalting.com/hydrosolar/clientGET.php?id=trendVolts&start=6400&size=200';
console.log(querystring);
jQuery.get(querystring, null, function (csv, state, xhr) {
if (typeof csv !== 'string') {
csv = xhr.responseText;
}
csv = csv.split(/\n/g);
var vB_array = [];
var iS_array = [];
jQuery.each(csv, function (i, line) {
if (line.length > 1) {
line_array = line.split(',');
var date = parseInt(line_array[0], 10) * 1000;
var vBpoint = {};
var iSpoint = {};
vBpoint.x = date;
iSpoint.x = date;
vBpoint.y = parseFloat(line_array[1]);
iSpoint.y = parseFloat(line_array[4]);
vB_array.unshift(vBpoint);
iS_array.unshift(iSpoint);
}
});
chart.series[0].setData(vB_array, false); // <<<<< Problem Area
chart.series[1].setData(iS_array, false);
chart.redraw();
});
chart.xAxis[0].setExtremes(); // expand out the scrollbar when moving through time:
}
});
here is the link
http://jsfiddle.net/pqKWj/14/
If you are interested let me know I see some more similar problems in the code, which I think fine for now, but will create issues, when you have 2 charts in the same page etc. we can talk
am trying to show data on highcharts that is comming from datatabase in code behind.
so far this is my code in javascript where the chart is drawn, testarray1,2, represents the data
function draw(d) {
var testarray = JSON.parse(a);
var testarray1 = JSON.parse(a1);
var testarray2 = JSON.parse(a2);
$(function() {
$('#container1').highcharts({
chart: {
type: 'column'
},
credits: {
enabled: false
},
title: {
text: 'Consumption by months'
},
xAxis: {
categories: array3
},
yAxis: {
title: {
text: 'kWh'
}
},
tooltip: {
valueDecimals: 2
},
plotOptions: {
type: 'column'
},
series: [{
name: '2011-2012',
type: 'column',
color: '#0000FF',
data: testarray
},
{
name: '2012-2013',
type: 'column',
color: '#92D050',
data: testarray1
}]
});
});
}
my output just shows the same data. what i need is some logic in the function draw do it refreshes when it draws, i have something like this.
var a = testarray
var b = testarray1
if (d == 1)
{
var c = a
}
else if (d == 2)
{
var c = b
}
else if (d == 1)
{
var d = a
}
else if (d == 1)
{
var d = b
}
with this i call c and d in the data. but i need a logic for 3 types of data, testarray, testarray1 and testarray2.
any ideas.