1
0

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 3 years have passed since last update.

chart.js使ってグラフ作成してみた

Posted at

#Railsで作成したアプリにグラフを簡単に入れる方法

##環境

ruby 2.5.0p0
Rails 5.2.4.2
slim

##サンプルイメージ

こんなグラフが簡単に出来上がります。

スクリーンショット 2020-05-12 18.20.43.png

##手順

gem インストール

$ gem 'chart-js-rails', '~> 0.1.4'
bundle install

chart.js インストール

package.json
{
  "name": "hoge",
  "private": true,
  "dependencies": {
    "chart.js": "^2.7.1" ←★追記
  }
}
$ yarn install

// = require Chart.min を追記

hoge/app/assets/javascripts/application.js

// = require Chart.min
// = require rails-ujs
// = require activestorage
// = require turbolinks
// = require_tree .

view側

app/views/hoge/index.html.slim
<canvas id="myChart" width="400" height="400"></canvas>
javascript:
  draw_graph();
hoge/app/assets/javascripts/hoge.coffee

window.draw_graph = -> 
    ctx = document.getElementById("myChart").getContext('2d')
    myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    })

動作確認

$ rails s

下記の記事を参考に自分でも試してみましたが、30分ぐらいですぐに作成することができました。アプリにグラフを導入してみたい方にオススメです。

次はユーザーが見やすいようにカスタマイズしていきます。

##参考記事

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?