LoginSignup
3
4

More than 5 years have passed since last update.

ggplotオブジェクトからlayerを削除する

Posted at

あんまり需要はないと思うけど,一応メモ。

ggplot2のレイヤー構造について

よく「ggplot2はレイヤー構造である」といわれます。これについては以前別途まとめたので以下の資料を参照してください:

ggplotのオブジェクトから眺めてみる

簡単に確認をしてみます。以下のようなggplotオブジェクトを準備します:

library(ggplot2)
g <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() +
  geom_line() +
  geom_smooth()
g
  #> `geom_smooth()` using method = 'loess'

unnamed-chunk-1-1.png

上記のプロットでは,geom_pointgeom_linegeom_smoothという3つの描画レイヤーがあります:

g$layers
  #> [[1]]
  #> geom_point: na.rm = FALSE
  #> stat_identity: na.rm = FALSE
  #> position_identity 
  #> 
  #> [[2]]
  #> geom_line: na.rm = FALSE
  #> stat_identity: na.rm = FALSE
  #> position_identity 
  #> 
  #> [[3]]
  #> geom_smooth: na.rm = FALSE
  #> stat_smooth: na.rm = FALSE, method = auto, formula = y ~ x, se = TRUE
  #> position_identity

ggplotオブジェクトからレイヤーを削除

さて本題です。

実のところ,この描画レイヤーはlistになっています:

is.list(g$layers)
  #> [1] TRUE

なので,レイヤーを取り除きたいならそのlistの要素を削除すればいいだけです:

g$layers[[2]] <- NULL
g$layers
  #> [[1]]
  #> geom_point: na.rm = FALSE
  #> stat_identity: na.rm = FALSE
  #> position_identity 
  #> 
  #> [[2]]
  #> geom_smooth: na.rm = FALSE
  #> stat_smooth: na.rm = FALSE, method = auto, formula = y ~ x, se = TRUE
  #> position_identity
g
  #> `geom_smooth()` using method = 'loess'

unnamed-chunk-4-1.png

どこで使えるかというのはよくわかりませんが,ggplotの理解には繋がるかなと思いました。

Enjoy!

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4