2
0

はじめに

rails7にグラフ(chart.js)を適応させた際の備忘録です

実装

毎度定番のstimulus-componetsにchart.jsがあったので、それを利用します

yarn add @stimulus-components/chartjs
app/javascript/controllers/index.js
import Chart from "@stimulus-components/chartjs";
application.register("chart", Chart);
app/views/charts/index.html.erb
<canvas
  data-controller="chart"
  data-chart-data-value="<%= @chart_data.to_json %>"
  data-chart-options-value="<%= @chart_options.to_json %>"
></canvas>
app/controllers/charts_controller.rb
  def index
    @chart_data = {
      labels: (Date.today.prev_year..Date.today).select { |day| day.day == 1 }.map { |a| a.strftime('%Y/%m') },
      datasets: [{
        type: 'line',
        label: 'スコア1推移',
        data: [26, 18, 63, 26, 61, 10, 46, 27, 23, 98, 39, 20],
        borderColor: '#F08080',
        backgroundColor: '#F08080',
        yAxisID: 'y'

      }, {
        type: 'line',
        label: 'スコア2推移',
        data: [71, 25, 69, 100, 97, 14, 47, 13, 86, 48, 33, 72],
        borderColor: '#6495ED',
        backgroundColor: '#6495ED',
        yAxisID: 'y'
      }, {
        type: 'line',
        label: 'PV数',
        data: [709, 678, 778, 23, 509, 541,
               666, 505, 563, 104, 972, 324],
        borderColor: '#008000',
        backgroundColor: '#008000',
        yAxisID: 'y1'
      }]
    }

    @chart_options = {
      responsive: true,
      scales: {
        y: {
          type: 'linear',
          display: true,
          position: 'left'
        },
        y1: {
          type: 'linear',
          display: true,
          position: 'right',
          grid: {
            drawOnChartArea: false
          }
        }
      }
    }
  end

image.png

以上!

さいごに

実装そのものはサクッとできたのですが、グラフを弄る際にV2、V3、V4で書き方が異なるため、迷走していました。
調べてみたところ、「stimulus-chartjs」では、以下の最新が割り当てられてましたので、公式のページを参照するのが一番でした(2024/7/12時点)
image.png

もし、ご利用される際はご注意ください。

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