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

时间:2017-08-05 22:57:08

标签: r

让我们先说:

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

现在假设我要为0.5到4.5之间的区域着色,如下所示:

enter image description here

我该怎么做?

我通过以下行破解了它

sapply(seq(0.05, 0.35, 0.01), function(x) lines(c(x, x), c(0, dbeta(x, 2, 5)), col = "yellow", lwd = 4))

2 个答案:

答案 0 :(得分:4)

您可以使用与ggplot2::stat_function类似的curve执行此操作:

library(ggplot2)

ggplot(data.frame(x = 0:1), aes(x)) + 
    stat_function(fun = dbeta, args = c(2, 5), geom = 'area', 
                  xlim = c(0.05, 0.35), fill = 'yellow') + 
    stat_function(fun = dbeta, args = c(2, 5))

如果您更喜欢像原始方法那样预处理数据而不是让ggplot为您进行插值,那么您可以使用更普通的geom_areageom_line来生成相同的图。< / p>

答案 1 :(得分:2)

自从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)

Area under curve