如何在密度分布图的两端添加两个阴影

时间:2017-02-28 15:21:07

标签: r ggplot2

如何在两端添加阴影,如下图所示?

我想将0到-.995和1.995的一端添加到Inf

plot

我在这里尝试了解决方案https://stackoverflow.com/a/4371473/3133957,但它似乎无法正常工作。

这里是我的代码

tmpdata <- data.frame(vals = t.stats)
qplot(x = vals,  data=tmpdata, geom="density",
      adjust = 1.5,
     xlab="sampling distribution of t-statistic",
     ylab="frequency") + 
    geom_vline(xintercept = t.statistic(precip, population.precipitation), 
               linetype = "dashed") +
    geom_ribbon(data=subset(tmpdata,vals>-1.995 & vals<1.995),aes(ymax=max(vals),ymin=0,fill="red",alpha=0.5))

1 个答案:

答案 0 :(得分:0)

您没有为您的问题提供数据集,因此我模拟了一个用于此答案的数据集。首先,制作密度图:

tmpdata <- data.frame(vals = rnorm(10000, mean = 0, sd = 1))
plot <- qplot(x = vals,  data=tmpdata, geom="density",
          adjust = 1.5,
          xlab="sampling distribution of t-statistic",
          ylab="frequency")

然后,提取ggplot使用的x和y坐标来绘制密度曲线:

area.data <- ggplot_build(plot)$data[[1]]

然后,您可以添加两个geom_area图层,通过以下方式在曲线的左右尾部进行着色:

plot + 
geom_area(data=area.data[which(area.data$x < -1.995),], aes(x=x, y=y), fill="skyblue") +
geom_area(data=area.data[which(area.data$x > 1.995),], aes(x=x, y=y), fill="skyblue")

这将给你以下情节:

enter image description here

请注意,您可以在此之后添加geom_vline图层(我将其删除,因为它需要您在问题中未提供的数据)。