1

Basically I wish to mitigate the amount of re-coding I have to do when creating new plots by only changing the reference to the "xvar" object below...

xvar<-"n_Age"

ggplot(data=dat4,aes(x=n_Age,y=Count))+
  geom_smooth()+
  labs(x=xvar, y="Count")

This code works ok in the "labs" part of the statement (as it is referencing text) however in the "aes" component I need to re-specify n_Age. Can I not just use some syntax that removes the quotation marks from the xvar object, to actually reference the object?

Thanks, Daniel.

Daniel
  • 11
  • 2
  • 1
    could you add your data to the question (e.g. using dput) to make this reproducible, thanks. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – dww Apr 19 '16 at 23:26
  • 1
    The last example on the `ggplot2::aes` help page shows how to do this. It's probably a duplicate question as well. – IRTFM Apr 19 '16 at 23:32

2 Answers2

5

You can specify aes_string instead of aes:

xvar<-"n_Age"

ggplot(data=dat4,aes_string(x=xvar,y="Count"))+
  geom_smooth()+
  labs(x=xvar, y="Count")
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 1
    `aes_string` was the function used in the two prior answers to similar questions that I found using the search strategy: `[r] pass character aes ggplot`: http://stackoverflow.com/questions/21230635/accesing-a-variable-in-a-ggplot-function/21230804#21230804, and http://stackoverflow.com/questions/24916502/creating-a-function-using-ggplot2/24916664#24916664 – IRTFM Apr 19 '16 at 23:51
  • Thank you for your help. – Daniel Apr 28 '16 at 23:36
1

This is one instance where I use get

# silly data
dat4 <- data.frame("n_Age"=rnorm(100), "Count"=1:100)

xvar<-"n_Age"

ggplot(data=dat4,aes(x=get(xvar),y=Count))+
  geom_smooth()+
  labs(x=xvar, y="Count")
lmo
  • 37,904
  • 9
  • 56
  • 69