はじめに
Rubyでペアプロットを作る場合のスニペット。
Google colaboratory で実行した場合
(改良前なので若干上と画像が違います)
環境
- Jupyter Notebook
- IRuby
- Daru::View
(Jupyter Notebook や IRuby の導入は済んでいるものとします)
あと、一応Google Colaboratoryを使うという手段もあります。
iris 読み込み
ここではrdatasets Gemを使う。
require 'daru'
require 'daru/view'
require 'rdatasets'
iris = RDatasets.load :datasets, :iris
iris.head(3)
Daru::View.plotting_library = :googlecharts # Google Colab ではその都度指定する必要あり
ペアプロットを描く その1
# Daru::View.plotting_library = :googlecharts # Google Colab ではその都度指定する必要あり
vector_names = iris[0..3].vectors.to_a
vector_names.each do |row|
plots = vector_names.map do |column|
if row != column
Daru::View::Plot.new(iris[column, row],
type: :scatter,
height: 100,
width: 100,
pointSize: 1)
else
Daru::View::Plot.new(iris[row],
title: row,
height: 100,
width: 100,
type: :histogram)
end
end
IRuby.display Daru::View::PlotList.new(plots).show_in_iruby
end
普通に頑張ってループまわして描いた感じです。これでも実用にたえると思いますが、見た目がややチープですね。
ペアプロットを描く その2
とりあえず見た目を改善します。
(なお「見た目」とは、コードの見た目ではなく、プロットの見た目のことを指しています)
# Daru::View.plotting_library = :googlecharts # Google Colab ではその都度指定する必要あり
vector_names = iris[0..3].vectors.to_a
opts = {
chartArea: { left: 5, right: 5, top: 5, bottom: 5 },
height: 100,
width: 100,
hAxis: {viewWindowMode: "maximized"},
vAxis: {viewWindowMode: "maximized"},
backgroundColor: '#f0f0f0',
gridlineColor: 'white',
colors: ['#4784BF']
}
vector_names.each do |row|
plots = vector_names.map do |column|
if row != column
Daru::View::Plot.new(iris[column, row], opts.merge(
type: :scatter,
pointSize: 1
))
else
Daru::View::Plot.new(iris[row], opts.merge(
title: row,
titlePosition: 'in',
type: :histogram
))
end
end
IRuby.display Daru::View::PlotList.new(plots).show_in_iruby
end
Seabornをリスペクトしてみました。先程よりも見やすくなったかと思います。
関数にしてみた
ほとんど何も変わっていない。
def pair_plot(df, width: 100, height: 100, color: '#4784BF')
vector_names = df.only_numerics.vectors.to_a
opts = {
chartArea: { left: 5, right: 5, top: 5, bottom: 5 },
height: height,
width: width,
hAxis: { viewWindowMode: 'maximized' },
vAxis: { viewWindowMode: 'maximized' },
backgroundColor: '#f0f0f0',
gridlineColor: 'white',
colors: [color],
adapter: :googlecharts
}
vector_names.each do |row|
plots = vector_names.map do |column|
if row != column
Daru::View::Plot.new(
df[column, row], opts.merge(type: :scatter,
pointSize: 1)
)
else
Daru::View::Plot.new(
df[row], opts.merge(title: row,
titlePosition: 'in',
type: :histogram)
)
end
end
IRuby.display Daru::View::PlotList.new(plots).show_in_iruby
end
end
Rのデータセットをペアプロットしてみよう
USArrests
require 'rdatasets'
df = RDatasets.datasets.USArrests
pair_plot(df, color: "green")
fgl
df = RDatasets.MASS.fgl
pair_plot(df, height:60, width: 60)
こんな感じで、描けるか描けないかでいったら、描ける。
おまけ
Species ごとに平均などを見たい場合は group_by
iris.Species.to_category
hoge = iris.group_by ["Species"]
hoge.mean
# hoge.max
# hoge.min
# hoge.median