YQ.Wang YQ.Wang - 2 months ago 8
R Question

Wrong colour when using facet_wrap()

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?

Answer

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"))