やりたいこと:
R で hist() を使って、ヒストグラムを描き、つまり、次のような感じ:
加えて、各階級の度数を表示する。
なお、データは Rに入っている iris を利用する。
1. やり方
irisの1列目のデータを利用する。今回は、わかりやすさのために、変数d に iris[,1] を代入しておく。つまり、変数d に分析したいデータ (ベクトル) が入っているものとする。ではズバリ、次のように書く:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
d <- iris[,1] #利用するデータを指定 | |
info <- hist(d) #ヒストグラムが描かれる | |
text(x=info$mids, y=1, info$counts) #各階級の度数を書き入れる (下部) |
2. 仕組み
変数infoの中には、次の通り、ヒストグラムを描くための情報が入っている (info で出てくる):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$breaks | |
[1] 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0 | |
$counts | |
[1] 5 27 27 30 31 18 6 6 | |
$density | |
[1] 0.06666667 0.36000000 0.36000000 0.40000000 0.41333333 0.24000000 0.08000000 0.08000000 | |
$mids | |
[1] 4.25 4.75 5.25 5.75 6.25 6.75 7.25 7.75 | |
$xname | |
[1] "d" | |
$equidist | |
[1] TRUE | |
attr(,"class") | |
[1] "histogram" |
このうち、今回関連のある情報は:
ですので、
- $counts が度数
- $mids が階級値 (階級の真ん中の値)
- x座標 = info$mids
- y座標 = 1 (この値は任意)
なお、y座標はお好みで。下にいくつか例をあげておく。
- hist() を拡張した myhist()はコチラ。
0 件のコメント:
コメントを投稿