为什么 R 中的函数曲线在超出函数边界时无法正确绘制?

问题描述 投票:0回答:1

假设我有给定边界内某种函数的概率分布函数。在这个边界内它的总面积当然是1。在此边界之外它被定义为零。

f <- function(z) 2*z^2 - 15*z + 15
fp <- function(x) f(x) * dunif(x, 10, 30) 
norm_const <- function(func, l=10, u=30) integrate(func, l, u)$value 
norm_pdf <- function(x) fp(x) / norm_const(fp)

现在如果我们使用R中的曲线函数(或ggplot2的geom_function)

curve(norm_pdf, 0, 40)

enter image description here

正如您所看到的,图形曲线不会在 x 值的下边界和上限处直接趋于零。我希望情节像下面的代码一样运行(参见红线)。然而,我希望当曲线两端都为零时,就变成一条通往无穷远的直线。基本上我想用图表来绘制曲线!由于某种原因,曲线似乎存在某种滞后效应?当它超出其界限时。

library(ggplot2)

ggplot() + geom_function(fun = norm_pdf) + xlab("x") + ylab("Density") + theme_minimal() + 
  scale_x_continuous(limits=c(0, 40), breaks=seq(0, 40,2)) + 
  geom_segment(aes(x = 10, y = 0, xend = 10, yend = norm_pdf(10)), color="red") +
  geom_segment(aes(x = 30, y = 0, xend = 30, yend = norm_pdf(30)), color="red") 
r ggplot2 plot limit curve
1个回答
0
投票

正如罗兰建议的那样,这解决了问题

curve(norm_pdf, 0, 40, n = 1e6)

对于 ggplot2 包,解决方案是

stat_function(fun = norm_pdf, n=10^6)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.