LoginSignup
1
1

More than 5 years have passed since last update.

Rメモ ヒストグラムの層別可視化

Last updated at Posted at 2018-08-11

営業数値やら各データを見る際に、まずは単純集計ですが、
代表格のヒストグラムは、何故かEXCELやスプレがポンコツで、
Rじゃないと作りにくいですよね。

(PythonとJupyterNotebookもありだと思いますが、
速攻!を目的にするならやはりRだと個人的に思っています。)

そんなhist機能ですが、層別で見る方法でちょっと検索に時間がかかったのでメモ。
(オプションも以外に逐次検索するので、ついでにメモ。)

ヒストグラムの層別化

ここでは2つの方法を紹介しています。
一つはノーマルhistで色を変えて重ね合わせる方法。
2つ目はライブラリでlatticeを使った方法。

よく使うオプションを下に追記しておきますので、カスタマイズ用に。

image.png

> hist(d[d$性別=="W",]$カラム名, breaks = 25, col = "#ff00ff40",ylim = c(0,5))
> hist(d[d$性別=="M",]$カラム名, breaks =100, col = "#0000ff40",add = TRUE)

image.png

> library(lattice)
> histogram(~カラム名|性別,data=d,col=0)

よく使うオプション

営業さん向けなので一応細かく書いときます。

hist_command.R
#ノーマル
> hist(d$カラム名)

#切り数を追加:breaks
> hist(d$カラム名,breaks = 25)

#頻度(割合)ラベルを表示:label
> hist(d$カラム名,breaks = 25, label = TRUE)

#頻度を割合に変換:freq
> hist(d$カラム名,breaks = 25, label = TRUE, freq = FALSE)

#表示する範囲を指定:xlim、ylim
> hist(d$カラム名,breaks = 25, label = TRUE, freq = FALSE, xlim = c(0,1000), ylim = c(0,0.003))

#軸名と題名を追加(日本語だと表示されないので注意):xlab、ylab、main
> hist(d$カラム名,breaks = 25, label = TRUE, freq = FALSE, xlim = c(0,1000), ylim = c(0,0.003), xlab = "x", ylab = "y", main = "Histgram")

#RGB値で色を追加(数字直接指定でも、"red"などもOK):col
> hist(d$カラム名,breaks = 25, label = TRUE, freq = FALSE, xlim = c(0,1000), ylim = c(0,0.003), xlab = "x", ylab = "y", main = "Histgram", col = "#ff00ff40")

#”性別”列の”W”だけに絞る:d[d$性別=="W",]$カラム名
> hist(d[d$性別=="W",]$カラム名, breaks = 25, label = TRUE, freq = FALSE, xlim = c(0,1000), ylim = c(0,0.003), xlab = "x", ylab = "y", main = "Histgram", col = "#ff00ff40")

#一つ前のグラフと重ね合わせる:add
> hist(d[d$性別=="W",]$カラム名, add = TRUE, breaks = 25, label = TRUE, freq = FALSE, xlim = c(0,1000), ylim = c(0,0.003), xlab = "x", ylab = "y", main = "Histgram", col = "#ff00ff40")

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