简体   繁体   English

情节中缺少手动图例(scale_colour_manual),具有多种美感

[英]Manual legend (scale_colour_manual) missing in plot with several aesthetics

I have just used ggplot to plot data from different data frames. 我刚刚使用ggplot从不同的数据帧绘制数据。 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. 需要将aes内的color变量映射为实际颜色,而aes外的颜色则不必要。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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