【R tips】ggplot2での出力設定メモ

ggplot2での作図時に困ったことの備忘録として。コードに誤りがあればご指摘ください。

y軸の余白を削除する

# import library ----
library(tidyverse)

# sample ----------
fig <- 
  iris %>% 
  group_by(Species) %>% 
  summarise(mean_splen = mean(Sepal.Length))

ggplot(data = fig) +
  geom_bar(mapping = aes(x = Species, y = mean_splen), stat = "identity") +
  scale_y_continuous(expand = expansion(mult = c(0, 0.1)))

標準ではy軸の0の下に余白があるが、scale_y_continuous()のexpandでグラフの下側、上側の余白の大きさを調整できる。

scale_y_continuous(expand = expansion(mult = c(下側の余白設定, 上側の余白設定))

連続量の場合、グラフ下端と軸の間には6%分の余白が設定されているよう。

factor型のグラフ出力順を制御する

# import library ----
library(tidyverse)

# sample ----------
fig <- 
  iris %>% 
  group_by(Species) %>% 
  summarise(mean_splen = mean(Sepal.Length))

ggplot(data = fig) +
  geom_bar(mapping = aes(x = fct_reorder(Species, mean_splen, .desc = TRUE),
                         y = mean_splen),
                         stat = "identity")

factor型をグラフに出力するとlevels順の出力になる。

並び順の変更にはlevelsの再設定が必要だが、factor型の操作には{forcats}パッケージの利用が便利。

よく使いそうなものは以下。

  • fct_reorder(): 他の変数の値を用いてlevelsを変更できる
  • fct_inorder(): データセット内の出現順でlevelsを変更できる
  • fct_freq(): データセット内の頻度順でlevelsを変更できる

(追記)きちんとまとまった資料がありました。

Reorder a variable with ggplot2
This post describes how to reorder a variable in a ggplot2 chart. Several methods are suggested, always providing exampl...

コメント

タイトルとURLをコピーしました