0

How to pass column name of a data frame in ggplot facet_wrap or fill/colour in a function? I looked up lazyeval but didn't figure out a way.

x="class"
ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x) 

In this example, why didn't the points get coloured by x?

santoku
  • 3,297
  • 7
  • 48
  • 76
  • 2
    Possible duplicate of http://stackoverflow.com/questions/21588096/pass-string-to-facet-grid-ggplot2 or http://stackoverflow.com/questions/11028353/passing-string-variable-facet-wrap-in-ggplot-using-r – akrun Apr 02 '17 at 13:30

2 Answers2

2

I used an example from ggplot2::facet_wrap. So, you can easily replace ~class with x containing a character or a formulae. Example :

library(ggplot2)
x="class"#or ~class
ggplot(mpg, aes(displ, hwy)) +
        geom_point() +
        facet_wrap(x)
Mamoun Benghezal
  • 5,264
  • 7
  • 28
  • 33
  • indeed. but how about color each facet? this doesn't seem to work. ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x) thank you – santoku Apr 02 '17 at 13:40
  • What do you mean by colouring each facet ? The points or the background ? – Mamoun Benghezal Apr 02 '17 at 13:44
  • the points, as in the snippet ggplot(mpg, aes(displ, hwy, col=x)) + geom_point() + facet_wrap(x) – santoku Apr 02 '17 at 13:51
  • you should use a variable containing an integer or a factor. Try `mpg$class2 <- factor(mpg$class); ggplot(mpg, aes(displ, hwy, col=class2)) + geom_point() + facet_wrap(~class);` – Mamoun Benghezal Apr 02 '17 at 15:32
0

Have you tried ggplot(mpg, aes(displ, hwy, col=as.factor(x))) + geom_point() + facet_wrap(~x) ?

jesstme
  • 604
  • 2
  • 10
  • 25