我真的很感激这方面的一些帮助.我完全不明白ggplot2是如何思考传说的!
该图表基于以下数据框架,称为"meltdf":
xval variable value
1 0.000000 Shortfall Risk 100.00
2 4.624457 Shortfall Risk 99.83
3 9.179656 Shortfall Risk 60.96
4 13.742579 Shortfall Risk 36.29
5 18.620338 Shortfall Risk 27.71
6 22.947704 Shortfall Risk 22.52
7 27.690638 Shortfall Risk 19.72
8 32.174379 Shortfall Risk 17.89
9 36.637940 Shortfall Risk 15.79
10 41.107962 Shortfall Risk 15.96
11 45.644065 Shortfall Risk 15.97
Run Code Online (Sandbox Code Playgroud)
该图表如下:
ggplot(data=meltdf,aes(x=xval,y=value))+
geom_line(size=1,colour=rgb(69,99,111,max=255))+
geom_vline(xintercept = 22 ,colour="darkgray")+
geom_vline(xintercept = 30 ,colour="darkred")+
theme_bw()+
labs(title="Shortfall Risk versus Investment Risk, Meeting Expenditure Only")+
theme(legend.position="bottom",
legend.text = element_text(size=9),
axis.text = element_text(size=9),
axis.title = element_text(size=9),
plot.title=element_text(size = 9),
legend.title=element_text(size=9))+
labs(x="Largest Historical Decline (%)", y="Probability of Shortfall (%)")+
scale_y_continuous(limits = c(0, 100))
Run Code Online (Sandbox Code Playgroud)
我想在底部有一个图例,其中图表中的所有三行(蓝色,红色和灰色)都被命名.
sco*_*coa 11
ggplot将自动生成在aes()调用中映射的元素(颜色,线型等)的图例.这意味着当您手动指定元素的颜色时,您将无法获得图例,就像您在此处所做的那样(所有colour语句都不在内部aes).
我建议您将垂直线的坐标存储在自己的数据框中,在这些数据框中,它们可以映射到给出颜色的变量.在这里,我创建了这样一个dataframe(summ)并重写了你的代码geom_vline().我也被映射meltdf$variable到colour在geom_vline所以它出现在传奇.最后,我添加scale_colour_manual()了选择颜色.您可能希望调整其值,summ$colour以便它们在图例中有意义.
summ <- data.frame(x=c(22,30),
colour=c("gray","red"))
ggplot(data=meltdf,aes(x=xval,y=value))+
geom_line(size=1,aes(colour=variable))+
geom_vline(data=summ,aes(xintercept = x,colour=colour))+
scale_color_manual(values = c(rgb(69,99,111,max=255),"darkgray","darkred")) +
theme_bw()+
labs(title="Shortfall Risk versus Investment Risk, Meeting Expenditure Only")+
theme(legend.position="bottom",
legend.text = element_text(size=9),
axis.text = element_text(size=9),
axis.title = element_text(size=9),
plot.title=element_text(size = 9),
legend.title=element_text(size=9))+
labs(x="Largest Historical Decline (%)", y="Probability of Shortfall (%)")+
scale_y_continuous(limits = c(0, 100))
Run Code Online (Sandbox Code Playgroud)