让我们开始说:
x <- seq(0, 1, 0.01)
y <- dbeta(x, 2, 5)
plot(x, y, type = "l")
Run Code Online (Sandbox Code Playgroud)
现在假设我想为 0.5 到 4.5 之间的区域着色,如下所示:
我该怎么做?
我通过以下行破解了它
sapply(seq(0.05, 0.35, 0.01), function(x) lines(c(x, x), c(0, dbeta(x, 2, 5)), col = "yellow", lwd = 4))
Run Code Online (Sandbox Code Playgroud)
您可以使用 来执行此操作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))
Run Code Online (Sandbox Code Playgroud)

如果您更愿意像原始方法一样预处理数据,而不是让 ggplot 为您插值,则可以使用更普通的geom_area并geom_line生成相同的图。