7
votes

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.

1
This is likely to do the order of evaluation. It will try to add the geom_point to geom_point before adding this to the plot. Might I recommend restructuring the function to receive p and x as parameters, and return the result of the function to p - Chris Littler
Depending on how complex it is what you want to achieve, you might want to create your own geom. Read this. - January

1 Answers

14
votes

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