LoginSignup
16
7

More than 3 years have passed since last update.

爆速で円グラフを実装する[5分]

Last updated at Posted at 2019-10-12

はじめに

今回は'chartkick'を使って爆速で円グラフを実装します。

Gemの導入

Gemfile
gem "chartkick"
gem 'chartable'
ターミナル
bundle install

javascriptライブラリの読み込み

application.js
//= require Chart.bundle
//= require chartkick

application.jsに上記を記載。

インスタンスメソッドの定義

tweets_controller.rb
def index
配列の場合
  @chart = [['国語', 10], ['算数', 20],['理科',30]['社会',40]]
ハッシュの場合
  @chart = {"国語" => 10, "算数" => 20, "理科" => 30, "社会" => 40}
end

配列でもハッシュでも可能です!!

viewページ

tweets/index.html.haml
= pie_chart @chart

この一行を追加するだけ!!

スクリーンショット 2019-10-12 15.40.17.png

こんなかんじですね。

備考

コントローラーの変数を変えればどんなグラフも作れます。
モデルから値を取得することが多いと思うので参考に載せておきます。

def index
  @chart = Post.order('created_at ASC').group(:name)
end

こんな感じです。

おわりに

めちゃめちゃ簡単です。
ビューページに一行書けば実装できます:relaxed::relaxed:
では

16
7
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
16
7