我已经绘制了一个分布,我想对> 95% 的区域进行着色。
但是,当我尝试使用此处记录的不同技术时:ggplot2 按组密度曲线下的阴影面积 https://stackoverflow.com/questions/20355849/ggplot2-shade-area-under-density-curve-by-group由于我的数据集的长度不同,它不起作用。
AGG[,1]=seq(1:1000)
AGG[,2]=rnorm(1000,mean=150,sd=10)
Z<-data.frame(AGG)
library(ggplot2)
ggplot(Z,aes(x=Z[,2]))+stat_density(geom="line",colour="lightblue",size=1.1)+xlim(0,350)+ylim(0,0.05)+geom_vline(xintercept=quantile(Z[,2],prob=0.95),colour="red")+geom_text(aes(x=quantile(Z[,2],prob=0.95)),label="VaR 95%",y=0.0225, colour="red")
#I want to add a shaded area right of the VaR in this chart
在这种情况下,ggplot 的辅助函数和内置摘要最终可能会带来麻烦而不是有用。在您的情况下,最好直接计算您的摘要统计数据,然后绘制它们。在下面的例子中,我使用density
and quantile
从基地stats
库来计算将绘制的内容。直接将其提供给 ggplot 最终比尝试操作 ggplot 的汇总函数简单得多。这样,阴影是通过使用来完成的geom_ribbon
和 ggplot 预期的美学系统;无需深入挖掘绘图对象。
rm(list = ls())
library(magrittr)
library(ggplot2)
y <- rnorm(1000, 150, 10)
cutoff <- quantile(y, probs = 0.95)
hist.y <- density(y, from = 100, to = 200) %$%
data.frame(x = x, y = y) %>%
mutate(area = x >= cutoff)
the.plot <- ggplot(data = hist.y, aes(x = x, ymin = 0, ymax = y, fill = area)) +
geom_ribbon() +
geom_line(aes(y = y)) +
geom_vline(xintercept = cutoff, color = 'red') +
annotate(geom = 'text', x = cutoff, y = 0.025, color = 'red', label = 'VaR 95%', hjust = -0.1)
print(the.plot)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)