ggplot2 - is there a way to override global aesthetic mappings while reusing geom layers

ggplot2, r

Solution

Swapping variables associated with aesthetics and the data associated with a plot are both straightforward. Using the `gg` you define in the question, use `aes` by itself to change aesthetics:

gg + aes(x=table, y=depth)

To change the data used for a plot, use the `%+%` operator.

dsamp2 <- head(diamonds, 100)
gg %+% dsamp2

Problem

By assigning a ggplot() object to a variable, one can easily reuse the object and make multiple versions of a plot with variations on the geom layers without redundant code for each plot. However, I was wondering if there's a way to reuse geom layers while swapping the global aesthetic mappings. One use case for this is that I want to make several plots with the same geometric representations, but want to swap out the variable mapped to one of the dimensions. Another use case is that I want to make two plots where the data come from two different data frames. The intuitive way to go about this would be to 1) save the combination of the geom layers to a variable without assigning a ggplot() object or 2) override the data and aesthetics of an existing ggplot() object in a variable by adding another ggplot() object. Doing either of these things causes errors though (for 1- "non-numeric argument to binary operator, for 2 - "Don't know how to add o to a plot"). For example, suppose in the following plot I want to re-use the gg variable but remap the x variable to something else in the dataframe: ``` dsamp <- diamonds[sample(nrow(diamonds), 1000), ] gg <- (ggplot(data = dsamp, aes(x = carat, y = price, color = clarity)) + geom_point() + facet_wrap(~ cut)) print(gg) ``` In practice plot definitions can be a lot more than 3 lines long, which is why this starts to be a code maintenance annoyance.

Original source