2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ggplotでプロットの型を使い回す(%+%)

Posted at

ggplotで、異なるデータで同じ形のプロットしたいときの一つのやり方。
%+% を使うことで、事前に作ったggplotオブジェクトを使いまわして、データを入れ替えできる。

まずは、プロットの型を作る。

R
g <- ggplot(data=iris, aes(x=Sepal.Length, Sepal.Width)) +
  geom_point() +
  xlim(4, 8) +
  ylim(1, 5)

※この時点で、dataは指定しなくても問題ない。(NULLなどでもよい)
 ちなみに、上記gを表示すると次のイメージ。
image.png

次に、データを入れ替える。(本題)

R
g %+%
  filter(iris, Sepal.Length < 6)

image.png

R
g %+%
  filter(iris, Sepal.Length >= 6)

image.png

もともとのプロットの型をアレンジすることも可能。
※なお下のコードは、もとのgeom_point()の後で、geom_point(color="blue")が再度処理されているイメージ。

R
g %+%
  filter(iris, Sepal.Length >= 6) +
  geom_point(color="blue") +
  geom_smooth(method="lm", color="black")

image.png

2
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?