add geom sub-parts to ggplot after geom has been previously added

Hi everyone,

I am writing a shiny app and a part of it allows users to draw plots with with a variety of customized elements. The logic I am designing this plotting function is writing a bunch of if statements go like this,

p = ggplot(data)
if(condition1){
  p = p + geom_x
} 
if(condition2){
  p = p + lable(x)
}

however, there is a problem int his design. Say we are in one if statement where we are asked to adjust the point size of a geom_point plot and the ggplot object generated from the previous if statements is this

p = ggplot(data) + geom_point(...) + geom_text(...)

My tentative solution is

to do

p + aes(size = selected size)

but how do I make sure this aes(size) goes to geom_point instead of geom_text?

This form problem could be further generalized to how can I add an element to geom_x after the geom_x was already added to the plot?

Thank you!

From a ggplot-perspective, you would do this by putting the fixed aesthetic value inside of `geom_point(), e.g.

geom_point(colour = "red", size = 3)

so, given that, you would want to essentially regenerate the geom_point(...) part of the plot.

There are a few ggplot extensions that allow for interactive editing of plots. The source code for those extensions might be a helpful place to look (even though I think these two are add-ins):

Otherwise, you might consider moving this to shiny, since I think this might be more about the logic of your shiny app than ggplot itself (though, of course, it's totally your call).

Hope this helps!

Mara

1 Like

Is it right to say there is not a way in ggplot2 that you can specify a geom_ to apply aes?

You absolutely can specify aes within geoms, e.g.:

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point(aes(colour = factor(cyl)))

I think @trcc is referring to "geom_*" as an argument of aes() somehow…