如何在密度分布图的两端添加两个阴影 [英] How can i add two shade on both end of the density distribution plot
问题描述
我如何像下面的图片一样在两端添加阴影?
How can i add shaded on both end like the picture below?
我想在0到-.995之间添加一个末端,在Inf上添加1.995
i want to add one end from 0 to -.995 and 1.995 to Inf
我在这里尝试了解决方法 https://stackoverflow.com/a/4371473/3133957 ,但似乎没有工作.
I tried solution here https://stackoverflow.com/a/4371473/3133957 but it doesn't seem to work.
这里是我的代码
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))
推荐答案
您没有为您的问题提供数据集,因此我模拟了一个用于该答案的数据集.首先,制作密度图:
You didn't provide a dataset for your question, so I simulated one to use for this answer. First, make your density plot:
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坐标:
Then, extract the x and y coordinates used by ggplot to plot your density curve:
area.data <- ggplot_build(plot)$data[[1]]
然后您可以通过以下方式添加两个geom_area
层以在曲线的左右尾部添加阴影:
You can then add two geom_area
layers to shade in the left and right tails of your curve via:
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")
这将为您提供以下情节:
This will give you the following plot:
请注意,您可以在此之后添加geom_vline
层(我省略了它,因为它需要您在问题中未提供的数据).
Note that you can add your geom_vline
layer after this (I left it out because it required data you did not supply in your question).
这篇关于如何在密度分布图的两端添加两个阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!