Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding multiple layers to a ggplot with a function

I am trying to add multiple graphical elements to an existing ggplot. The new elements will be placed around a specified x-value. Simplified, I have the existing plot p with one point at the origin:

library(ggplot2)
p <- ggplot(data = data.frame(x = 0, y = 0), aes(x = x, y = y)) +
  geom_point()

Now I want to make a function that can add a point left and right, based on a defined x-position. I tried:

add_points <- function(x) {
  geom_point(aes(x = x - 1, y = 0), color = "red") +
  geom_point(aes(x = x + 1, y = 0), color = "red")
}

But when I try to add them using

p + add_points(x = 0)

I get

Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

What is the ggplot way of adding multiple layers based on a function that takes an argument?

PS: only adding one layer using this function does work, so first creating a tibble with the x-values and feeding that to the geom_point instead also works. In reality however, I am adding several different geoms to the plot, so I think I need to add several layers together in the function.

like image 829
MartijnVanAttekum Avatar asked Jul 11 '19 13:07

MartijnVanAttekum


1 Answers

From help("+.gg"):

You can also supply a list, in which case each element of the list will be added in turn.

add_points <- function(x) {
  list(geom_point(aes(x = x - 1, y = 0), color = "red"),
    geom_point(aes(x = x + 1, y = 0), color = "red"))
}

p + add_points(x = 0)
#works
like image 146
Roland Avatar answered Sep 20 '22 13:09

Roland