Railsでグラフ表示

仕事で売上げデータの集計結果をグラフ表示する機会があったのでlazy_high_chartsを使ってみた。

インストール

  • Gemfile
gem 'lazy_high_charts'

app/assets/javascripts/application.js

以下を追記

//= require highcharts

app/controllers/sample_controller.rb

class SampleController < ApplicationController
  def show
    @end_at = Date.today
    @start_at = @end_at - 6
    @categories = @start_at.upto(@end_at).to_a
    @data1 = Array.new(7){rand(10)}
    @data2 = Array.new(7){rand(10)}

    @h = LazyHighCharts::HighChart.new('graph') do |f|
      f.title(text: 'Total')
      f.xAxis(categories: @categories)
      f.series(name: 'data1', yAxis: 0, data: @data1, type: 'column')
      f.series(name: 'data2', yAxis: 1, data: @data2)

      f.yAxis [
        {title: {text: 'data1'}},
        {title: {text: 'data2'}, opposite: true}
      ]

      f.options[:chart][:defaultSeriesType] = 'spline'
    end
  end
end

app/views/samples/show.html.erb

<%= high_chart("total", @h) %>

出力は以下のような感じ。

f:id:i2bs:20130207221140p:plain