2

The df consists of two normal variables:a,b, one colour variable:c and one group variable:d

df<-data.frame(c(1:5,11:15),c(1:10),c(1,1,1,1,1,2,1,2,1,2),c(rep('o',5),rep('m',5)))
colnames(df)<-c('a','b','c','d')

I want to have o and m groups in one plot, so I do the following:

qplot(a,b,data=df,geom = 'point',color=factor(df$c))+facet_wrap(~d)+scale_colour_manual(values=c("blue","orange"))

enter image description here The colour of the plot result is wrong, according to df, group m is supposed to have blue and orange points. Why does this happen? How could I do the right plot?

This question is similar to Behavior ggplot2 aes() in combination with facet_grid() when passing variable with dollar sign notation to aes(). My case suggests that never use $ or [ in not only aes() but also facet_wrap()

Community
  • 1
  • 1
YQ.Wang
  • 1,090
  • 1
  • 17
  • 43

1 Answers1

3

Don't use $ notation in ggplot aesthetics. Use raw variable names instead:

qplot(a,b,data=df,geom='point',color=factor(c)) + 
  facet_wrap(~d) + 
  scale_colour_manual(values=c("blue","orange"))
Axeman
  • 32,068
  • 8
  • 81
  • 94
  • This really helps, thanks a lot! By the way, how can I locate these two groups in one colume with two row rather than one row with two columes as ploted above? – YQ.Wang Sep 30 '16 at 09:24
  • 1
    That should work: facet_wrap(facets, **nrow = NULL, ncol = NULL**, scales = "fixed", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE, dir = "h") – m-dz Sep 30 '16 at 09:25
  • 1
    Read ?facet_wrap and note the nrow argument. – Axeman Sep 30 '16 at 09:26
  • When I use `facet_wrap(~d,nrow = 2)`, I got `Error in plyr::eval.quoted(vars, data, emptyenv(), try = TRUE) : envir must be either NULL, a list, or an environment.` – YQ.Wang Sep 30 '16 at 11:10
  • @YQ.Wang It works fine for me. – Axeman Sep 30 '16 at 11:23
  • Oh, I forgot to generate the test dataframe. My fault. – YQ.Wang Sep 30 '16 at 11:34