本当に必要なグラフの描き方(ggplot2編)
TableauやGoogle Data Studioなど、BIツールを利用するようになって思ったこと。
「もう、ggplotで目盛りの細かい調節をしたり、カラーコードを一生懸命調べたりしなくても、視覚化はこいつらに任せればいいな…」
少なくとも自分にとっては、ggplotのメインの役割は【EDAの中で行う可視化】になった。
そのときに使うグラフの種類はそこまで多くないのだが、一方で線種の指定はlinetype=
だったかlinestyle=
だったかなど、いつも忘れてしまうので備忘
ヒストグラム
geom_histogram(aes(x, colour=グルーピング変数))
棒グラフ
- 集計値を
y
として使う場合
geom_bar(aes(x, y, fill=グルーピング変数), stat='identity')
- 積み上げ棒グラフ
geom_bar(aes(...), stat='identity', position='stack')
- 積み上げ100%棒グラフ
geom_bar(aes(...), stat='identity', position='fill')
折れ線グラフ
geom_line(aes(x, y, group=グルーピング変数[, colour=グルーピング変数] [, linetype=グルーピング変数]))
- マーカー付
+ geom_point(aes(x, y, colour=グルーピング変数[, shape=グルーピング変数]))
- ラベル付
+ geom_text(aes(x, y, label=集計値, colour=グルーピング変数))
散布図
geom_point(aes(x, y, colour=グルーピング変数), alpha=0.3~0.7) geom_jitter(aes(x, y, colour=グルーピング変数), alpha=0.3~0.7)
箱ひげ図
geom_boxplot(aes(x=グルーピング変数, y))
軸の表示範囲の固定
xlim
.ylim
にはNULL指定可
+ coord_cartesian(xlim=c(**,**), ylim=c(**,**))
facet
facet_grid(行側 ~ 列側, scales = 'free' or 'free_x' or 'free_y') facet_wrap(~ ., scales = 'free' or 'free_x' or 'free_y')
タイトル、軸ラベル
+ ggtitle() + xlab() + ylab()