How to list dates (day-by-day) on xAxis using HighCharts

二次信任 提交于 2019-12-08 11:52:13

问题


I'm trying to display dates (i.e., by day) along the xAxis using HighCharts. I'm using the Lazy High Charts gem w/ Rails to do so. For the HighCharts 'data' argument, I'm passing in a nested array with [[date, revenue], [date, revenue], [date, revenue]...etc].

The yAxis with the revenue is working correctly, but the corresponding date in the xAxis is not.

Here's the controllers code :

def graph_orders

        sales_and_date_array = []

        Order.revenue_to_array(sales_and_date_array)

        puts sales_and_date_array.inspect

        # http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/series/data-array-of-arrays-datetime/

        @chart = LazyHighCharts::HighChart.new('graph') do |f|
          f.title(:text => "Lono Sales")
          f.xAxis(
            type: 'datetime'
           )

          f.series(:name => "Lono Sales Revenue", :yAxis => 0, :data => sales_and_date_array)

          f.yAxis [
            {:title => {:text => "Revenue", :margin => 70} },
            {:title => {:text => "Revenue"}, :opposite => true},
          ]

          f.legend(:align => 'right', :verticalAlign => 'top', :y => 75, :x => -50, :layout => 'vertical',)
          f.chart({:defaultSeriesType=>"line"})
        end

    end

Here's what inpsecting 'sales_and_date_array' looks like:

[["2014-06-12", 208.28], ["2014-06-11", 416.56], ["2014-06-11", 624.84], ["2014-06-11", 833.12], ["2014-06-10", 1041.4], ["2014-06-09", 1249.68], ["2014-06-08", 1457.96], ["2014-06-08", 1666.24], ["2014-06-07", 1874.52], ["2014-06-07", 2082.8], ["2014-06-07", 2291.08],....etc

Here's what the graph output currently looks like:

Any thoughts?


回答1:


Highcharts does not accept dates in that format. You can either pass a Date.UTC object, or you can pass the date in javascript epoch format (in milliseconds).

references:

  • http://www.epochconverter.com/

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

  • What format does the highcharts js library accept for dates?




回答2:


Exact example:

@chart = LazyHighCharts::HighChart.new('graph') do |f|
  f.title(:text => 'History')
  f.xAxis(:type => 'datetime',
          :title => {
            text: 'Date'
          })
  f.yAxis(:title => {
            text: 'Values'
          })
  f.series(:name => 'Value',
           :data => YourModel
                      .map { |i| [i.created_at.to_time.to_i * 1000,
                                  i.your_value] })

  f.chart({:defaultSeriesType => 'line'})


来源:https://stackoverflow.com/questions/24212785/how-to-list-dates-day-by-day-on-xaxis-using-highcharts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!