因此,我正在尝试向R图添加自定义图例。我正在尝试添加此图例,以说明我的情节中的线条:
因此,我的目标是要有一个传说,说蓝线代表标准偏差。
到目前为止,这是我的代码:
kernal.dens <- ggplot(daily.ret2.df, aes(x=Daily,color = year))+
geom_density(data = filter(daily.ret2.df, year != 2019),adjust=2, size=1, show.legend = T)+
geom_density(data = daily.ret2.12,adjust=2, size=1.75, show.legend = T)+
geom_segment(lty=1,aes(x = sd(daily.ret2.12$Daily),xend = sd(daily.ret2.12$Daily),
yend = 5,y = 0),color = "blue",size = .5)+
geom_segment(lty=1,aes(x = sd(daily.ret2.12$Daily)*2,xend = sd(daily.ret2.12$Daily)*2,
yend = 5,y = 0),color = "blue",size = .5)+
geom_segment(lty=1,aes(x = sd(daily.ret2.12$Daily)*-1,xend = sd(daily.ret2.12$Daily)*-1,
yend = 5,y = 0),color = "blue",size = .5)+
geom_segment(lty=1,aes(x = sd(daily.ret2.12$Daily)*-2,xend = sd(daily.ret2.12$Daily)*-2,
yend = 5,y = 0),color = "blue",size = .5)+
scale_color_manual(values=c( "black", '#3A8026', "#7F8931", "#C4933D","#C47422", "#C45608",
"#B12F08", "#9E0808", "#80262D"),
labels = c(' Last 12 Months ',' 2011 ',' 2012 ',' 2013 ',' 2014 ',' 2015 ',' 2016 ',
' 2017 ',' 2018 '))+
legendGrob(labels = 'Sd',do.lines = T,nrow = 1,ncol = 1)+
grid.legend(draw = T)+
scale_x_continuous(breaks = seq(-.1,.1,.05),
labels = paste0(seq(-.1,.1,.05)*100,'%'))+
scale_y_continuous(breaks = seq(0,50,5))+
labs(x='\nReturn\n',y='Density\n',title=paste0(asset, ' Daily Return Densities\n'))+
theme(plot.title=element_text(hjust=.5,size=44-max(0,nchar(asset)-6),face='bold'),
axis.text=element_text(size=20,color='black',face='bold'),
axis.title=element_text(size=28,color='black',face='bold'),
legend.text=element_text(size=18,color='black',face='bold'),
legend.title=element_blank(),
legend.position = 'bottom',
plot.margin=unit(c(1,1,1,1),"cm"))
当我把它放进去时,我得到这个错误:
Error: Don't know how to add legendGrob(labels = "Sd", do.lines = T, nrow = 1, ncol = 1) to a plot
我认为错误是R没有数据知道图例中每个项目对应的情节。
每当我看到一个添加自定义绘图的示例时,已经有一个旧绘图要替换,但是就我的情况而言,我想要一个不存在的绘图。
感谢您的时间,无论您有什么能力帮助我。我也很乐意在R和相关主题中添加图例以进一步了解它们的任何建议。