ggplot2 中密度曲线下的阴影区域

Shaded area under density curve in ggplot2

我已经绘制了一个分布图,我想对大于 95 个百分位数的区域进行阴影处理。 但是,当我尝试使用此处记录的不同技术时: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

这是一个使用函数 WVPlots::ShadedDensity 的解决方案。我将使用这个函数,因为它的参数是不言自明的,因此可以很容易地创建情节。不利的一面是,定制有点棘手。但是,一旦您围绕 ggplot 对象进行了思考,您就会发现它并不那么神秘。

library(WVPlots)

# create the data
set.seed(1)
V1 = seq(1:1000)
V2 = rnorm(1000, mean = 150, sd = 10)
Z <- data.frame(V1, V2)

现在您可以创建情节了。

threshold <- quantile(Z[, 2], prob = 0.95)[[1]]
p <- WVPlots::ShadedDensity(frame = Z, 
                            xvar = "V2",
                            threshold = threshold,
                            title = "Your title",
                            tail = "right")
p

但是因为你想要线条的颜色是淡蓝色等,所以你需要操作对象p。在这方面,另请参阅 and 问题。

对象 p 包含四层:geom_linegeom_ribbongeom_vlinegeom_text。您可以在这里找到它们:p$layers.

现在你需要改变他们的审美映射。对于 geom_line 只有一个,即 colour

p$layers[[1]]$aes_params
$colour
[1] "darkgray"

如果您现在想将线条颜色更改为浅蓝色,只需像这样覆盖现有颜色即可

p$layers[[1]]$aes_params$colour <- "lightblue"

一旦你想出了如何为一个 layer 做到这一点,剩下的就很简单了。

p$layers[[2]]$aes_params$fill <- "grey"     #geom_ribbon
p$layers[[3]]$aes_params$colour <- "red"    #geom_vline
p$layers[[4]]$aes_params$label <- "VaR 95%" #geom_text

p

现在的情节是这样的

在这种情况下,ggplot 的辅助函数和内置摘要最终可能会带来麻烦而不是帮助。在你的情况下,最好直接计算你的汇总统计数据,然后绘制它们。在下面的示例中,我使用基础 stats 库中的 densityquantile 来计算将绘制的内容。将其直接提供给 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)