ng150716
ng150716

Reputation: 2244

Creating a Simple Line Chart with Highcharts

I'm having a bit of difficulty creating a line chart with some JSON time series data I have. My JSON data looks like this:

[{
  'close': 30.1361,
  'date': '2017-07-05'
}, {
  'close': 29.7583,
  'date': '2017-07-06'
}, {
  'close': 29.9326,
  'date': '2017-07-07'
}]

Additionally I am serving up my web pages via Django/Python, so the JSON data above is store in a variable that looks like this: {{ one_yr|safe }}

Currently I have a blank chart with the numbers 0-140 across the y-axis and nothing on the x-axis, with no plot. My code thus far looks like this:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Django Highcharts Example</title>
</head>
<body>
  <div id="container"></div>
  <script src="https://code.highcharts.com/highcharts.src.js"></script>
  <script>
    Highcharts.chart('container', {
        chart: {
            type: 'line'
        },
        title: {
            text: 'One Year Stock Price'
        },
        series: [{
            name: '{{ stock.ticker }}',
            data: {{ one_yr|safe }}
        }]
    });
  </script>
</body>
</html>

I'm hoping to create a very simple line chart with dates on the x-axis and prices on the y-axis. Any help would be much appreciated, thanks.

Upvotes: 0

Views: 2909

Answers (1)

rafaelncarvalho
rafaelncarvalho

Reputation: 729

You need to convert your JSON for the Highcharts format, since Highcharts need both axis in the object and the datetime as UNIX timestamp.

You also need to add the datetime type in your xAxis.

My fiddle: https://jsfiddle.net/1ro6hqy8/

var one_yr = [{
  'close': 30.1361,
  'date': '2017-07-05'
}, {
  'close': 29.7583,
  'date': '2017-07-06'
}, {
  'close': 29.9326,
  'date': '2017-07-07'
}]

one_yr = one_yr.map(function(e) {
  return {
    'y': e.close,
    'x': new Date(e.date).getTime()
  }
})

Highcharts.chart('container', {
  title: {
    text: 'One Year Stock Price'
  },
  xAxis: {
    type: 'datetime',
    dateTimeLabelFormats: {
      day: '%e of %b'
    }
  },
  series: [{
    data: one_yr
  }]
});

Upvotes: 2

Related Questions