0

Can anyone get me started with a highstock chart to render the following remote JSON data into a line graph? I would just like to render a simple line graph right now on successful ajax fetch, but the date in the data below includes an hourly value.

poolprice

container: panelone

[{"date":"11/24/2012 19","price":"126.44"},{"date":"11/24/2012 18","price":"244.31"},{"date":"11/24/2012 17","price":"90.83"},{"date":"11/24/2012 16","price":"38.78"},{"date":"11/24/2012 15","price":"70.56"},{"date":"11/24/2012 14","price":"80.83"},{"date":"11/24/2012 13","price":"45.0"},{"date":"11/24/2012 12","price":"47.15"},{"date":"11/24/2012 11","price":"54.53"},{"date":"11/24/2012 10","price":"59.03"},{"date":"11/24/2012 09","price":"42.67"},{"date":"11/24/2012 08","price":"43.04"},{"date":"11/24/2012 07","price":"43.53"},{"date":"11/24/2012 06","price":"42.93"},{"date":"11/24/2012 05","price":"38.57"},{"date":"11/24/2012 04","price":"31.83"},{"date":"11/24/2012 03","price":"29.27"},{"date":"11/24/2012 02","price":"24.46"},{"date":"11/24/2012 01","price":"24.21"},{"date":"11/23/2012 24","price":"22.34"},{"date":"11/23/2012 23","price":"22.34"},{"date":"11/23/2012 22","price":"29.66"},{"date":"11/24/2012 20","price":"57.83"},{"date":"11/25/2012 02","price":"79.58"},{"date":"11/25/2012 01","price":"79.3"},{"date":"11/24/2012 24","price":"76.95"},{"date":"11/24/2012 23","price":"176.27"},{"date":"11/24/2012 22","price":"86.83"},{"date":"11/24/2012 21","price":"67.63"}]

Thanks :)

AC

ac360
  • 211
  • 2
  • 12

1 Answers1

1

The data is not sorted, and comes with a date format that Highstock can't parse. The date has to be parsed into a Date object, converted to a timestamp for Highstock to use, and sorted.

// Parse data into (unordered) array of timestamp and value
var newData = new Array();
for (var i = 0; i < rawData.length; i++) {
    var row = rawData[i];
    var date = new Date(row.date.substring(6, 10), parseInt(row.date.substring(0, 2)) - 1, row.date.substring(3, 5), row.date.substring(11, 13), 0, 0);
    var data = [date.getTime(), parseFloat(row.price)];
    newData.push(data);
}

// Sort the data by time. Thanks to Ben Blank: http://stackoverflow.com/questions/5199901/how-to-sort-an-associative-array-by-its-values-in-javascript
var tuples = new Array();
for (var key in newData) {
    tuples.push([key, newData[key]]);
}

tuples.sort(function(a, b) {
    a = a[1];
    b = b[1];
    return a < b ? -1 : (a > b ? 1 : 0);
});

var orderedData = [];
for (var i = 0; i < tuples.length; i++) {
    var key = tuples[i][0];
    var value = tuples[i][1];
    orderedData.push(value);
}

This fiddle shows your line chart.

OyvindK
  • 100
  • 1
  • 1
  • 7