Rのggplot2で「あー,こんなのあったら良いのになぁぁ!!!悔しいなぁぁ!!!」って時に役立ちそうな,細かいテクニックを紹介するシリーズ第2弾です。ggplotの基本的な文法が分かっている人向けの記事です。
今回の問題
あるグラフをグループごとに作成し縦横に並べて表示したい場合,facet_grid()を使うことが多いと思います。特にtheme()を弄らなければ,グループごとにパネルの枠があるため問題ないようですが(下左図),theme()に変更を加えパネル枠を外した場合,一番外側のパネル以外のパネルの軸が消えてしまいます(下右図)。これでは見た目が悪いので,全てのパネルに軸線が欲しいです。今回はその対処法を紹介します。
ggplotを使っている殆どの人が知らなくていいテクニックですが,研究論文ではグラフ内の線を細かく設定したいことが多いので,Rで解析をして研究論文を書く人は知っていて損はないと思います。
パッケージ準備
library(dplyr) library(ggplot2)
問題の再現
irisを使って,SpeciesごとにSepal.Lengthのヒストグラムのfacet_gridで描いてみましょう。theme()の中で,panel.borderで外側のパネル枠を外し,axis.lineで軸線を足してみます。
iris %>% ggplot(aes(x = Sepal.Length)) + geom_histogram(position = "identity") + theme_bw() + theme(panel.border = element_blank(), # remove panel axis.line = element_line(), # put axis line axis.ticks = element_blank()) -> p left <- p + facet_grid(Species~.) # Graph on the left right <- p + facet_grid(.~Species) # Graph on the right
左右どちらのグラフでも,軸側のパネルの以外の軸線が消えました。ちなみに,facet_wrapを用いても問題は解決できません。
facet_rep_gridで簡単に解決
lemonというパッケージにあるfacet_rep_gridを用いると,簡単に解決できます。lemonってなんか可愛いですね。facet_gridと同じ文法で用いることができて,scalesも指定できます。全てのパネルに軸線を入れられ,スケールの表示を外側のパネルにのみ残せます。
install.packages("lemon") library(lemon) left <- p + facet_rep_grid(Species~.) # Graph on the left right <- p + facet_rep_grid(.~Species)# Graph on the right
グラフの清書
最後にfacet_rep_gridを使い,かつ体裁を最大限整えたグラフを描いてみます。論文にもそのまま使えるほど綺麗なので,参考にしてください。
library(dplyr) library(ggplot2) library(lemon) iris %>% ggplot(aes(x = Sepal.Length, fill = Species)) + geom_histogram(position = "identity", size = 0.2, color = "grey80", size = 0.2) + facet_rep_grid(Species~., scales = "free") + scale_x_continuous(breaks = seq(4, 8, 0.5)) + scale_y_continuous(expand = c(0,0)) + scale_fill_brewer(palette = "Set1") + theme_bw() + theme(panel.border = element_blank(), panel.spacing = unit(1, "lines"), axis.line = element_line(color = "grey40", size = 0.3), axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8), axis.title = element_text(size = 8), strip.background = element_blank(), strip.text = element_text(size = 8, face = "bold"), axis.ticks = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.position = "none")
終わり。