まずは蝋の翼から。

学んだことを書きながら確認・整理するためのメモブログ。こういうことなのかな?といったことをふわっと書いたりしていますが、理解が浅いゆえに的はずれなことも多々あると思うのでツッコミ歓迎

ggplot2覚書⑦ theme詳細 facet

引き続き「Rグラフィッククックブック」。

過去記事は以下。

ggplot2覚書① 棒グラフ - まずは蝋の翼から。

ggplot2覚書② 散布図 - まずは蝋の翼から。

ggplot2覚書③ 注釈(解釈補助) - まずは蝋の翼から。

ggplot2覚書④ 軸について - まずは蝋の翼から。

ggplot2覚書⑤ 体裁(theme、テキストgeom)に関しての大枠 - まずは蝋の翼から。

ggplot2覚書⑥ theme詳細 凡例の設定 - まずは蝋の翼から。

facetラベルとヘッダの体裁

themeを用いて体裁を整える。
stripがfacetに対して。strip.text でfacetのテキスト部分、strip.backgroundでfacetの背景(ヘッダの背景)についてとなる。

なお、facet_gridにおいて、ラベルをデフォルトと逆の位置(xは上部→下部、yは左部→右部)にしたい場合はswichで指定する(両方に場合はboth)。

library(gcookbook) # データセットの読み込み 
library(patchwork)

g1 <- ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) +
  geom_bar(stat="identity") + 
  facet_grid(. ~ Date) + 
  theme(strip.text.x = element_text(face="bold", size=rel(1.5), angle = 180),
        strip.background = element_rect(fill="lightblue", colour="black", size=1))

g2 <- ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) +
  geom_bar(stat="identity") + 
  facet_grid(. ~ Date, switch = "x") + 
  theme(strip.text.x = element_text(face="bold", size=rel(1.5), angle = 90),
        strip.background = element_rect(fill="lightblue", colour="black", size=1))

g1 / g2

f:id:chito_ng:20190223223552p:plain

ラベルを目盛の外にしたい場合はstrip.placement に "outside"を指定する。

library(gcookbook) # データセットの読み込み 
library(patchwork)

g1 <- 
  ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) +
  geom_bar(stat="identity") + 
  facet_grid(. ~ Date) + 
  theme(strip.text.x = element_text(face="bold", size=rel(1.5)),
        strip.background = element_rect(fill="lightblue", colour="black", size=1)) +
  labs(title = "defalt position")

g2 <-
  ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) +
  geom_bar(stat="identity") + 
  facet_grid(. ~ Date, switch = "x") + 
  theme(strip.text.x = element_text(face="bold", size=rel(1.5)),
        strip.background = element_rect(fill="lightblue", colour="black", size=1))+
  labs(title = "bottom position")

g3 <-
ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) +
  geom_bar(stat="identity") + 
  facet_grid(. ~ Date, switch = "x") + 
  theme(strip.text.x = element_text(face="bold", size=rel(1.5)),
        strip.background = element_rect(fill="lightblue", colour="black", size=1),
        strip.placement = "outside") +
  labs(title = "outside bottom position")

g1 / g2 / g3

f:id:chito_ng:20190225200518p:plain