Search code examples
ruby-on-railsjsonhighchartslazy-high-charts

Lazy HighCharts and Loading Json Data


I'm using LazyHighCharts and trying to collect json data to display only the last 24hrs, but it's not displaying the data, just the date but only once (there should be a temperature each hour of the day).

data structure

{"status": "ok", "data": [{"2014-06-16 16:00:00": 24.2},{"2014-06-17 12:00:00": 30.2},{"2014-06-18 17:00:00": 42.9}]} etc

Controller

@data = JSON.parse(open(@temperature.url).read)

dates = []
temps = []

@data['data'].each do |data|
 dates << data.keys
 temps << data.values
end 

@graph = LazyHighCharts::HighChart.new('graph') do |f|
 f.chart(:height => '400')
 f.yAxis [:title => {:text => "Temperature", :margin => 20, style: { color: '#333'}}]
 f.series(:pointInterval => 1.hour, :pointStart => 30.day.ago, :type => 'area', :name => '24hrs', :data => [[dates, temps]])
 f.options[:xAxis] = { :minTickInterval => 24 * 3600 * 1000, :type => "datetime", :dateTimeLabelFormats => { day: "%b %e"}, :title => { :text => nil }, :labels => { :enabled => true } }
end

Image

enter image description here


Solution

  • to convert your datetime object to the JS milliseconds convention, just call

    DateTime.now.to_i*1000 
    

    or in your case

    def index
      @data = {"status" => "ok", "data" => [{"2014-06-16 16:00:00" => 24.2},{"2014-06-17 12:00:00" => 30.2},{"2014-06-18 17:00:00" => 42.9}]}
      d = []
      @data['data'].each do |data|
        d << [DateTime.parse(data.keys.first).to_i*1000, data.values.first]
      end 
    
      @chart = LazyHighCharts::HighChart.new('chart') do |f|
        f.chart(:height => '400')
        f.yAxis [:title => {:text => "Temperature", :margin => 20, style: { color: '#333'}}]
        f.xAxis(type: 'datetime')
        f.series(:type => 'area', :name => '24hrs', :data => d)
      end
    end