Problem showing data from a csv file for highcharts - javascript

I am trying to create a highchart line graph using data from a .csv file. But my webpage is just showing the titles of x and y axis, but no data. The code is as follows:
$(document).ready(function() {
var c = [];
var d = [];
$.get('data.csv', function(data) {
alert("data in the file: " + data);
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'Weight Monitor'
},
xAxis: {
title: {
text: 'Date Measured'
},
categories: c
},
yAxis: {
title: {
text: 'Weight (in Lbs)'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
i tried to print the data read from file on screen just to check if the file was read properly and i got the proper data, but still my graph is not showing anything.
following is the data in my csv file:
2011-08-01 00:00:00,155
2011-08-02 00:00:00,156
2011-08-03 00:00:00,157
2011-08-03 00:00:00,160
where left value is date to be shown in x axis and right value is reading points for graph.
any help will be thankful.

Your code works perfect.
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
Copy this whole code and save it as .html file in a directory and create the data.csv file in the same directory and make sure that there no empty lines, no spaces where they are not needed and no line-break at the end.
And then open the .html file, the chart should show up with the right data.

Add the chart within $.get.
Note that we can't create the chart outside the Ajax callback, as we have to wait for the data to be returned from the server. See this.
$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
var chart = new Highcharts.Chart(options);
},'Text');
Also mention explicitly the data return type to "Text" which might be a problem some time.

You must read the documentation properly. See http://www.highcharts.com/documentation/how-to-use#preprocessing
They already have a demo of the csv http://highcharts.com/studies/data-from-csv.htm .
Please go through the docs and familiarise yourself ! .

Related

How to combine two Highcharts chart types?

Right now I have a simple column chart with following code using Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
//some code
},
xAxis: {
categories: []
},
yAxis: {
//some code
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y}'
}
}
},
legend: {
//some code
},
series: []
};
$.getJSON("data/column.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
I now want to add a line chart to the same container, using exactly the same options (despite of the chart type). The date is also served via JSON.
How can I achieve this?
What I did so far:
I created a second variable "options2" with values chart and series.
Then I called
$.getJSON("data/line.php", function(json) {
options.xAxis.categories = json[0]['data'];
options2.series[1] = json[1];
chart = new Highcharts.Chart(options2);
});
But that only shows the first column chart.
Probably you should try use $.merge to prevent object edition.
Try this
$.getJSON("data/column.php", function(json) {
// Merge objects
var newOptions = $.extend({}, options);
// Edit new object instead of old
newOptions.xAxis.categories = json[0]['data'];
newOptions.series[0] = json[1];
chart = new Highcharts.Chart( newOptions );
});
Solved it by passing the series option (chart type) directly via JSON.
I added the "type:line" to the data array, which then overrides previously set options within the script tag.

Highcharts downsampling - CSV

I'm developping a web-app and I use the JS Highcharts plugin to help me to draw some charts. Sometimes I load a CSV file with more than 100 000 lines with 4 columns.
Obviously, the chart plugin meet some problems. So, I can't downsample my CSV file directly but, I found a Downsampling Highcharts plugin (http://www.highcharts.com/plugin-registry/single/13/Highcharts-Downsample) that do the job !
But in fact, this plugin may only initialize a serie with a threshold value .. And I don't know how to apply this method on my series loaded by CSV ..
I load my CSV like that instead of "series" attribute specified by the plugin Usage :
data: {csv: csv},
The plugin doc tells us to use it like that :
series: [{
downsample: {
threshold: 1000 // 0 disables downsampling for this series.
},
data: // Your data (array of arrays with two values or array of numerical values)
}]
But I don't use "series" attribute because I load my series directly from a CSV file ..
So, I want to find a solution to downsample my CSV file using this Downsampling Hicharts plugin ..
Thank you so much !
So, finally, i found a solution !
I parse my CSV file myself and I can specify the downsample attribute :
var options = { //Initialize my chart's option
chart: {
zoomType: 'x',
renderTo: $('#chart-'+unused)[0]
},
title: {
text: elem.title
},
credits: {
enabled: false
},
xAxis: {
categories: [], //initialize empty category array
type: "line"
},
yAxis: {
title: {
text: "milli-SI"
}
},
series: [] //initialize empty serie array
};
var lines = csv.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
if (itemNo > 0) {
var series = {
data: [],
name: item,
downsample : {threshold: 2000} //initialize downsample for a specific serie
};
options.series.push(series);
}
});
}
else {
$.each(items, function(itemNo, item) {
if (item.length == 0)
return;
if (itemNo == 0) {
options.xAxis.categories.push(item);
} else {
options.series[itemNo -1].data.push(parseFloat(item));
}
});
}
});
var chart = new Highcharts.Chart(options);

how to solve Highcharts error #15?

Hello friends I'm trying to draw the chart using javascript function the data comes into JSON array format like
[[1432116687000,5100],[1432116991000,5100],[1432117291000,5100],[1432117591000,5100],[1432117894000,5100],[1432118199000,5100],[1432118499000,5100],[1432118800000,5100],[1432119100000,5100],[1432119404000,5100],[1432119648000,5100],[1432119950000,5100],[1432120250000,5100],[1432120550000,5100],[1432120850000,5100],[1432121154000,5100],[1432121154000,5100]]
But I'm getting an error
Highcharts Error #15
Highcharts expects data to be sorted
This happens when you are trying to create a line series or a stock chart where the data is not sorted in ascending X order. For performance reasons, Highcharts does not sort the data, instead it is required that the implementer pre-sorts the data.
please help me to fix it
function drawChart(data){
console.log(data);
var date = [];
var ttc = [];
var series = [];
for(var i=0; i<data.length; i++){
//date.push(data[i][0]);
//console.log(date);
//ttc.push(parseInt(data[i][1]));
//console.log(ttc);
series.push([data[i][0],parseInt(data[i][1])]);
}
//console.log(data[i][1]);
//var series = (series);
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: 'Area Per TCC'
},
yAxis: {
title: {
text: 'TTC'
}
},
series: [{
name: 'TCC',
data: series
}]
});
} ;

How to format Highcharts columnRange to get json data for temperature Min and Max

I'm trying to display information on Highcharts from the forecast.io api. With the help of others on this site, I have figured out how to call the data using a simple line or area chart; however, I can't figure out how to with the columnRange chart. I want to display the daily min and max temperature forecast. So the top column would display today's min and max temp, and the next column would be tomorrows, and so on.
To call the min and max for today from forecast.io:
data.daily.data[0].temperatureMin
data.daily.data[0].temperatureMax
Tomorrows would have a "1" instead of a 0. The day after would have a "2".
I haven't been able to figure out how to make a function that does this for each day. I have a jsfiddile which includes my forecast.io API key. This is needed to call from the source.
Anyways, any help would be much appreciated! http://jsfiddle.net/nn51895/gjw9m1qo/2/
(my x axis labels are really messed up as you will see..)
$(function () {
$('#container').highcharts({
chart: {
type: 'columnrange',
inverted: true
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
valueSuffix: '°F'
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
formatter: function () {
return this.y + '°F';
}
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Daily Min and Max',
data: 'ChartData',
pointStart: new Date().getTime(),
pointInterval:90000000,
}]
});
});
$.ajax({
url: "https://api.forecast.io/forecast/87a7dd82a91b0b765d2576872f2a3826/53.479324,-2.248485",
jsonp: "callback",
dataType: "jsonp",
success: function(chart) {
var dataArr = new Array();
var height = chart.xAxis[0].height;
var pointRange = chart.daily.data[0].temperatureMax - chart.daily.data[0].temperatureMin;
var max = chart.daily.data[0].temperatureMax;
var min = chart.daily.data[0].temperatureMin;
var pointCount = (max - min) / pointRange;
var timeint = chart.daily.data[0].time;
for(var i=0; i<chart.daily.data.length; i++)
dataArr.push(chart.daily.data[i].temperatureMin);
plotChart(dataArr, timeint)
}
});
First of all, as said in the comment:
success: function (chart) {
...
var height = chart.xAxis[0].height;
}
You are trying to get for some unknown reason height of xAxis from the chart. Meanwhile you chart variable is referring to the data from AJAX call. I hope that's clear, so remove that line or change to:
success: function (chart) {
var myChart = $('#container').highcharts();
var dataArr = new Array();
var height = myChart.xAxis[0].height;
}
Second thing, that option:
data: 'ChartData',
Is wrong, there should be an empty array, since Highcharts requires array for data, not some string:
data: [],
Now, after fixing these bugs, you should go to this demo and create the same data format. That's example for required format for Highcharts.
More about series.data can be found in API reference - you need to read this.

Displaying a json file with highstock

I have some difficulties displaying a graph with Highstock. It seems like I can't have access to the x-axis part where the graph should be displayed. I am new with Highstocks so my code could seem like a mess but my idea was the following:
First access the json file from the server. Convert it in the right format [[datestamp, value], ....]. Then display the graph.
Here is my Json file (file.json):
[{"date":"2013-10-04T22:31:12.000Z","value":30000},{"date":"2013-10-04T22:31:58.000Z","value":35000},{"date":"2013-10-04T22:32:05.000Z","value":60000},{"date":"2013-10-04T22:32:12.000Z","value":45000}]
My code is the following:
$(function() {
chartOjb = new Object();
var mydata = [];
$.getJSON('file.json', function(data) {
$.each(data, function (index, item) {
chartOjb.name = getTimestamp(item.date);
chartOjb.data = item.value;
mydata.push({ x: chartOjb.name, y: parseFloat(chartOjb.data) });
});
$('#container').highcharts('StockChart', {
chart: {
type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: mydata
}
},
scrollbar: {
liveRedraw: false
},
xAxis: {
type: 'datetime',
title: 'Time',
//minRange: 3600 * 1000/15 // one hour
},
rangeSelector : {
selected : 1
},
title : {
text : value
},
series : [{
name : 'Capacité',
data : data,
tooltip: {
valueDecimals: 2
}
}] }); });
});
Thank you very much for your help
Could you add your function getTimestamp()? Maybe there is something wrong.
Keep in mind that:
x-value should be timestamp,
when using a lot of objects { x: x, y: y }, set turboThreshold

Categories

Resources