rggplot2textexpression-evaluation

Evaluating a plus symbol from parsed text as a ggplot2 operator


Questions like this one explain how to evaluate a parsed string, but this doesn't seem to work when a + is inside the string as an operator for combining layers of a ggplot.

E.g.

ggplot(data = mtcars) + eval(parse(text = "geom_point(aes(x = cyl, y = disp))"))

works, but this doesn't:

ggplot(data = mtcars) + 
  eval(parse(text = "geom_point(aes(x = cyl, y = disp)) + theme_bw()"))

Is there another way to evaluate the + operator in the ggplot context?


Solution

  • Following @Axeman's insight, here's a way to do what you want:

    p <- ggplot(data = mtcars)
    eval(parse(text = "p + geom_point(aes(x = cyl, y = disp)) + theme_bw()"))
    

    The reason this works is that R uses the class of the first object in a sum to dispatch to the right method to handle it. In your original example that failed, the first object was geom_point(aes(x = cyl, y = disp)) with a different class than ggplot(data = mtcars) has.