繁体   English   中英

在ggplot2中添加带有图例的任意系列?

[英]Add arbitrary series with legend in ggplot2?

我有一堆数据-三个时间序列(模型组均值),按组着色,标准偏差由geom_ribbon表示。 默认情况下,它们的侧面有一个漂亮的图例。 我也有一个观测值的时间序列,我想将其覆盖在绘图上(没有geom_ribbon),像这样:

df <- data.frame(year=1991:2010, group=c(rep('group1',20), rep('group2',20), rep('group3',20)), mean=c(cumsum(abs(rnorm(20))),cumsum(abs(rnorm(20))),cumsum(abs(rnorm(20)))),sd=3+rnorm(60))
obs_df <- data.frame(year=1991:2010, value=cumsum(abs(rnorm(20))))
ggplot(df, aes(x=year, y=mean)) + geom_line(aes(colour=group)) + geom_ribbon(aes(ymax=mean+sd, ymin=mean-sd, fill=group), alpha = 0.2) +geom_line(data=obs_df, aes(x=year, y=value))

但是观察结果确实出现在图例上,因为它没有颜色(我希望它是黑色的)。 如何将obs添加到图例?

首先,创建dfobs_df的组合数据框:

dat <- rbind(df, data.frame(year = obs_df$year,  
                  group = "obs", mean = obs_df$value, sd = 0))

情节:

ggplot(dat, aes(x=year, y=mean)) +
geom_line(aes(colour=group)) +
geom_ribbon(aes(ymax=mean+sd, ymin=mean-sd, fill=group), alpha = 0.2) +
scale_colour_manual(values = c("red", "green", "blue", "black")) +
scale_fill_manual(values = c("red", "green", "blue", NA))

情节

我猜您在构建“ obs_df”时出错了。 如果使用year = 1991:2010创建它,则在其余数据的上下文中更有意义,并且可以在ggplot更改ggplot调用的情况下为您提供希望的图。

暂无
暂无

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

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