R使用polygon填充曲线下区域时报错x、y长度不一致如何解决
错误原因
你报错的核心原因是错误使用了R中的冒号运算符::
- 你的
x1=0.5、x2=0.7是数值,x1:x2在R中会生成从x1开始每次步长为1的整数序列,实际返回的只有0.5这一个值,根本不是你想取的密度曲线中x坐标介于0.5到0.7之间的所有点的索引 - 这就导致你传入polygon的x、y向量长度不一致,触发报错
修复方案
先通过逻辑判断筛选出密度曲线x坐标落在[x1, x2]区间内的所有点的索引,再用该索引提取对应坐标构造多边形即可,修复后完整可运行代码如下:
n_samples <- 1e4 p_grid <- seq( from=0 , to=1 , length.out=1000 ) prior <- rep( 1 , 1000 ) likelihood <- dbinom( 6 , size=9 , prob=p_grid ) posterior <- likelihood * prior posterior <- posterior / sum(posterior) samples <- sample( p_grid , prob=posterior , size=n_samples , replace=TRUE ) x1 <- 0.5 x2 <- 0.7 dens <- density(samples) plot(dens) # 筛选区间内的点索引 idx <- dens$x >= x1 & dens$x <= x2 with(dens, polygon(x = c(x1, x[idx], x2), y = c(0, y[idx], 0), col = "gray"))
可选优化
如果需要让填充区域的边缘更平滑,可以在调用density函数时增加采样点数,例如:
dens <- density(samples, n = 2048)
内容的提问来源于stack exchange,提问作者z8080
相关产品推荐
相关产品推荐

