Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: Create a new geom based on the combination of two geoms

Tags:

r

ggplot2

I have two geoms, for instance geom_smooth and geom_point. I would like to create a new separate geom, geom_smoothpoint, which would draw the two aforementioned geoms.

I would like this:

ggplot(iris, aes(x=Sepal.Length, y=Petal.Width)) +
  geom_smoothpoint()

to give the same results as below:

ggplot(iris, aes(x=Sepal.Length, y=Petal.Width)) +
  geom_point() +
  geom_smooth(method="lm")

enter image description here

I have tried combining these two:

geom_smoothpoint <- function(){
  geom_point() +
  geom_smooth(method="lm")
}

But it doesn't really work. It seems that I must combine ggproto objects, but I am not sure how. Is there any simple way of combining two geoms into one? Thank you!

like image 492
Dominique Makowski Avatar asked Sep 09 '25 14:09

Dominique Makowski


1 Answers

You could of course write your own geom but this is an absolute overkill. It is much easier to return a list in your function which you can conveniently add to your plot:

geom_smoothpoint <- function() {
   list(geom_point(), geom_smooth(method = "lm"))
}

ggplot(iris, aes(x=Sepal.Length, y=Petal.Width)) +
   geom_smoothpoint()
like image 173
thothal Avatar answered Sep 12 '25 05:09

thothal