简体   繁体   中英

Manual legend (scale_colour_manual) missing in plot with several aesthetics

I have just used ggplot to plot data from different data frames. Somehow, I cannot get the (manual) legend to show up.

The code sample below is a good summary of the issue. What's the mistake?

library(plyr)
library(ggplot2)

df <- data.frame(gp=factor(rep(letters[1:3], each=10)), y=rnorm(30))

ds <- ddply(df, .(gp), summarise, mean=mean(y), sd=sd(y))

ggplot() +
  geom_point(data=df, aes(colour='one', x=gp, y=y), colour='red') +
  geom_point(data=ds, aes(colour='two', x=gp, y=mean), colour='green') +
  geom_errorbar(data=ds, aes(colour='three', x=gp, y=mean, ymin=mean-sd, ymax=mean+sd), colour='blue') +
  scale_color_manual('', values=c('red', 'green', 'blue'))

Please do not suggest that I combine the data in a single data frame and then group it by a new variable. I know this could be an option but it is in fact not possible in my particular case for reasons which are out of the scope of this question.

You were almost there. The color variable inside the aes needs to be mapped to an actual colour, and the colour outside aes is unncessary.

ggplot() +
  geom_point(data=df, aes(colour='one', x=gp, y=y)) +
  geom_point(data=ds, aes(colour='two', x=gp, y=mean))+
  geom_errorbar(data=ds, aes(colour='three', x=gp, y=mean, ymin=mean-sd, ymax=mean+sd))+
  scale_color_manual(values=c(one='red', two='green', three='blue'),
                     breaks=c("one","two","three"))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM