2
1

More than 3 years have passed since last update.

chart.jsとgonでグラフを作成する

Last updated at Posted at 2020-08-15

railsのcontrollerからgemのgonで変数を渡し
chart.jsでグラフを作成したので記録に残します。

chart.js読み込み

application.htmlに貼り付け

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"</script> ← 追加
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
</head>

show.html

<canvas id="myChart" width="150" height="80"></canvas>  ←サイズ大きかったので変更してます

jsファイルにグラフを記入

<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["赤", "青", "黄色", "緑", "紫", "橙"],
        datasets: [{
            label: '得票数',
            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
                }
            }]
        }
    }
});
</script>

こちらは

https://misc.0o0o.org/chartjs-doc-ja/

日本語ドキュメントを引用させていただきました!
使用方法に載ってました。

ここでshowページに棒グラフ作られたので次はrailsのcontrollerからjavascriptに変数を渡していきます。

Gonインストール

gem 'gon',  '~> 6.2.0'
bundle install

application.html

<%= include_gon %>
...省略
</head>

先ほどの読み込みの上に貼りました。

@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}
gon.your_int = @your_int       
gon.your_other_int = 345 + gon.your_int
gon.your_array = @your_array
gon.your_array << gon.your_int
gon.your_hash = @your_hash

gon.all_variables # > {:your_int => 123, :your_other_int => 468, :your_array => [1, 2, 123], :your_hash => {'a' => 1, 'b' => 2}}
gon.your_array # > [1, 2, 123]



引用:https://github.com/gazay/gon

ハッシュも配列も入れることができるそうです。

私はpetの体重をグラフにして行きたかったので、

 @pet = Pet.find(params[:pet_id])

 gon.weight = Condition.where(pet_id: @pet.id).pluck(:weight)
 gon.recorded_date = Condition.where(pet_id: @pet.id).pluck(:recorded_date)

Conditionテーブルのweightカラムでpet_idで絞り、gon.weightに代入しました。(X軸)
Conditionテーブルのrecorded_dateは日にちです。(Y軸)

https://teratail.com/questions/193183

参考にさせていただきました。
ありがとうございます。

これを先ほどのjsファイルに入れます。



var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: gon.recorded_date, <= 変更
    datasets: [{
      label: '体重',  <= 変更
      data: gon.weight, <= 変更
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
      ],
      borderColor: [
        'rgba(255,99,132,1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});

折れ線グラフが良かったのでtype:'line'にしましたが
ドキュメントにたくさんのtypeが載っていました。

以上です。
まだまだできそうなことがたくさんあるので触って行きたいです:v_tone1:

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