对两点之间的核密度图进行着色. [英] Shading a kernel density plot between two points.

查看:35
本文介绍了对两点之间的核密度图进行着色.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用核密度图来说明分布.这些在 R 中创建起来既简单又快速,如下所示:

I frequently use kernel density plots to illustrate distributions. These are easy and fast to create in R like so:

set.seed(1)
draws <- rnorm(100)^2
dens <- density(draws)
plot(dens)
#or in one line like this: plot(density(rnorm(100)^2))

这给了我这个漂亮的小 PDF:

Which gives me this nice little PDF:

我想对 PDF 下第 75 到 95 个百分位数的区域进行着色.使用 quantile 函数很容易计算点:

I'd like to shade the area under the PDF from the 75th to 95th percentiles. It's easy to calculate the points using the quantile function:

q75 <- quantile(draws, .75)
q95 <- quantile(draws, .95)

但是我如何在 q75q95 之间的区域着色?

But how do I shade the the area between q75 and q95?

推荐答案

使用 polygon() 函数,请参阅其帮助页面,我相信我们在这里也有类似的问题.

With the polygon() function, see its help page and I believe we had similar questions here too.

您需要找到分位数值的索引才能获得实际的 (x,y) 对.

You need to find the index of the quantile values to get the actual (x,y) pairs.

给你:

x1 <- min(which(dens$x >= q75))  
x2 <- max(which(dens$x <  q95))
with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="gray"))

输出(由 JDL 添加)

Output (added by JDL)

这篇关于对两点之间的核密度图进行着色.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆