如何在R中为分布曲线下的区域着色

如何在R中为分布曲线下的区域着色,r,R,让我们先说: x <- seq(0, 1, 0.01) y <- dbeta(x, 2, 5) plot(x, y, type = "l") 您可以使用ggplot2::stat_函数执行此操作,该函数类似于曲线: 库(ggplot2) ggplot(数据帧(x=0:1),aes(x))+ stat_函数(fun=dbeta,args=c(2,5),geom=area, xlim=c(0.05,0.35),填充=‘黄色’+ stat_函数(fun=dbeta,args=c(2,5)

让我们先说:

x <- seq(0, 1, 0.01)
y <- dbeta(x, 2, 5)
plot(x, y, type = "l")

您可以使用
ggplot2::stat_函数
执行此操作,该函数类似于
曲线

库(ggplot2)
ggplot(数据帧(x=0:1),aes(x))+
stat_函数(fun=dbeta,args=c(2,5),geom=area,
xlim=c(0.05,0.35),填充=‘黄色’+
stat_函数(fun=dbeta,args=c(2,5))


如果您希望像原始方法那样预处理数据,而不是让ggplot为您插值,您可以使用更普通的
geom_区域
geom_线
生成相同的绘图。

因为您从
plot
开始,基本的R解决方案是:

x <- seq(0, 1, 0.01)
y <- dbeta(x, 2, 5)
plot(x, y, type = "l")

x2 <- seq(0.05,0.35,0.01)
y2 <-  dbeta(x2, 2, 5)
x2 = c(0.05,x2,0.35)
y2 = c(0,y2,0)
polygon(x2,y2, col="yellow", border=NA)

x如果在多边形之后绘制直线,例如,使用
plot(x,y,type='n')
初始化,绘制多边形,然后绘制曲线(dbeta(x,2,5),add=TRUE)
,则可以保持直线清晰。
x <- seq(0, 1, 0.01)
y <- dbeta(x, 2, 5)
plot(x, y, type = "l")

x2 <- seq(0.05,0.35,0.01)
y2 <-  dbeta(x2, 2, 5)
x2 = c(0.05,x2,0.35)
y2 = c(0,y2,0)
polygon(x2,y2, col="yellow", border=NA)