ipetrik ipetrik - 11 days ago 7
R Question

changing x/y column without editing original ggplot command

(I will be using the

mtcars
dataframe from the
gcookbook
library.)

Let's say I generate the following plot:

p <- (ggplot(mtcars, aes (col = factor(cyl), x = wt, y = disp))
+ geom_point (shape = 19)
+ geom_text (aes(y=disp+0.1,label=hp), size = 2.5, vjust=0)
+ stat_smooth(method=lm))
plot(p)


enter image description here

Is there anyway I can change, for instance, the
x
or
y
or
col
, without having to go back and edit the original?

For instance, lets say I want to change
x
to
mpg
and
col
to
gear
. I'd like to just run something like,

p + ggplot(aes=aes (col = factor(gear), x = mpg))
plot(p)


but the first command gives the error:

Error: Don't know how to add o to a plot


Is there any way to change what columns are used in the plot without having to go back and edit the original command?

Answer

To change the overall aesthetics for the plot, you can do:

p + aes(color = factor(gear), x = mpg)

To change the aesthetics of specific layers you can manually change the object p by assigning new variables. This seems fragile, though.

To change the aesthetic mapping for the geom_text layer in your example:

p$layers[[2]]$mapping$label = mtcars$wt
p$layers[[2]]$mapping$y = mtcars$disp + 2