3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【rails】データをグラフで表示する

Posted at

前提

Rails 5.2.4.2

gem追加

Gemfile
gem'lazy_high_charts'
terminal
bundle install

javascriptライブラリの読み込み

app/assets/javascripts/application.js
//= require highcharts/highcharts

コントローラにグラフを描画するアクションを記載

app/controllers/application_controller.rb
  def index
    ...
    cities = House.pluck(:city).uniq.sort
    people = House.pluck(:num_of_people).uniq.sort
    max_people = people.max
    min_people = people.min

    @chart2 = LazyHighCharts::HighChart.new("graph") do |c|
      c.title(text: "地域毎の世帯あたりの人数(子供なし世帯)")
      #x軸
      c.xAxis(categories: people, title: {text: 'Number of households' } )
      #y軸
      c.yAxis(title: {text: 'count' } )

      cities.each do |city|
        family_has_nochild = []
        for num in min_people..max_people do
          #グラフ化したいデータを条件指定して抽出し、配列に入れる
          family_has_nochild << House.where(city: city).where(num_of_people: num).where(has_child: "No").count
        end
        #グラフ表示したいデータを配列で渡す
        c.series(name: city, data: family_has_nochild )
      end
      #凡例
      c.legend(align: 'right', verticalAlign: 'top', x: -100, y: 180, layout: 'vertical' )
      #グラフ種別を指定(棒グラフ)
      c.chart(type: "column" )
    end
   ...

ビューで表示したいグラフを読み込む

app/views/houses/index.html.haml
.wrapper
  %h1
    = "Houseデータのグラフ"
  .wrapper__guide
    = "インポートしたHouseデータ(csv)のグラフを表示します"

  .wrapper__chart
    .wrapper__chart__first
      # グラフの読み込み
      = high_chart("my_chart2", @chart2)
    .wrapper__chart__second
      # グラフの読み込み
      = high_chart("my_chart3", @chart3)

結果

image.png

参考

https://qiita.com/kazumons/items/c435b14fb637dfeeb4e6
https://www.school.ctc-g.co.jp/columns/masuidrive/masuidrive20.html

補足

グラフの色などの表示についての細かい設定はどうやるねん?

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?