Search code examples
sqlruby-on-railsruby-on-rails-3.2highchartslazy-high-charts

created_at date for xAxis highcharts


Below is the code that I now have. This gives me a 2 dimensional array (array of arrays) of the data I need which is perfect, because from what I can tell that's the best way to do what I am looking for with Highstock.

I think the last step I have to do is get it into the proper format for highstock: Date.UTC(2012, 9, 12)

I want it to look like this: http://jsfiddle.net/DkgVr/4/

Any idea how I can get the date to be like that?

The array right now looks like this: [[Thu, 13 Sep 2012, 215.0], [Wed, 12 Sep 2012, 211.0]]

Users Controller

@weight_items = Weight.order("date DESC").select('weights.content,  weights.date').all

Highstock

<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
    window.chart = new Highcharts.StockChart({
        chart: {
            renderTo: 'weight_chart',
            type: 'line',
            marginRight: 20,
            marginBottom: 25
        },
        title: {
            text: 'Your Weight Over Time',
            x: -20 //center
        },
        yAxis: {
            title: {
                text: 'Weight'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },

        legend: {
            layout: 'vertical',
            align: 'center',
            verticalAlign: 'bottom',
            x: -10,
            y: 100,
            borderWidth: 0
        },

        scrollbar: {
          enabled: true
        },

        rangeSelector : {
            selected : 1
        },

        credits: {
            enabled: false
        },


        series: [{
            tickInterval: <%= 1.day * 1000 %>,
            pointStart: <%= 3.weeks.ago.at_midnight.to_i * 1000 %>,
            name: 'Weight',
            data: <%= weight_and_date_array = @weight_items.map{|row| [row.date.to_date, row.content.to_f] } %>

        }]
    }, 

    function(chart){

        // apply the date pickers
        setTimeout(function(){
            $('input.highcharts-range-selector', $('#'+chart.options.chart.renderTo))
                .datepicker()
        },0)


      });
  });

});
</script>

Solution

  • You don't need

    xAxis: {
                type: 'datetime'
           }
    

    For HighStock. Also

    {
        pointInterval: <%= 1.day * 1000 %>,
        pointStart: <%= 3.weeks.ago.at_midnight.to_i * 1000 %>,
        name: 'Weight',
        data: <%= Weight.pluck(:content).reverse %>
    }
    

    not required for Highstock. Keep name and data only.

    Interval can be specified using tickInterval in the X Axis options.

    EDIT: After your edit, It seems that you are having problem in adding date in HighStock compliant format.

    So, Add dates in UTC. Convert dates into UTC using Ruby, HighStock library will pickit automatically.