LoginSignup
2
1

More than 1 year has passed since last update.

RailsでPlotly を使ってグラフ表示する

Last updated at Posted at 2019-06-19

chartkickに続いてPlotlyも使うっぽいのでこちらも動作までのメモ

ライブラリのダウンロード

公式よりライブラリをダウンロードし、vendor/assets/javascriptsにファイルを配置。 公式:https://plot.ly/javascript/getting-started/

Gem追加

Ruby側で定義した変数をJS側に渡すためにgonを導入する
Gemfile
gem 'gon'

gonの使用

turblinksの前に読み込まないと上手く動作しないので記述場所に注意。
views/layouts/application.html.erb
<%= Gon::Base.render_data %>

JSライブラリのprecompile

config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( plotly-latest.min.js )

JSライブラリのinclude

以下をグラフ表示したいページの末尾で記述してライブラリをincludeする
xxx.html.erb
<%= javascript_include_tag 'plotly-latest.min' %>

JSライブラリの使用

```ruby:assets/javascripts/application.js #= require plotly-latest.min ```

jsファイルの作成

window.onloadしないとerbより先にjsが読み込まれてDOMが取得できないので注意
assets/javascripts/graphs.js
window.onload = function graph_test() {
  TESTER = document.getElementById('tester');
  Plotly.plot( TESTER, [{
    x: gon.x,
    y: gon.y }],{
    margin: { t: 0 }
    }
  );
}

coffeeファイルの削除

controllerをgenerateするとcoffeeファイルが作成されてしまっているので削除する。 こいつが残ってるとcoffeeが優先されて上記jsを読み込んでくれない。

参考

Ruby on Rails を利用したwebアプリにplotly.jsを使いグラフを描画する https://xhateblo.hatenablog.com/entry/rails/view/js/plotly
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