绘制曲线函数

Plot Curve Function

为什么红色曲线不与绿色重叠curve()

我注意到,如果将操作保存在中间对象上,然后我们将这些对象传递给 curve() 函数,它就可以正常工作。我的兴趣是通过在 curve() 中进行操作来理解为什么它不起作用。我觉得很好奇。

set.seed(1L)
x <- rnorm(n = 1e3L, mean = 200, sd = 30)
hist(x, probability = TRUE, ylim = c(0, 0.015))
curve(dnorm(x = x, mean = 200, sd = 30), col = "black", lty = 1, lwd = 2, add = TRUE) # OK
curve(dnorm(x = x, mean = 199.6506, sd = 31.04748), col = "green", lty = 1, lwd = 2, add = TRUE) # OK
curve(dnorm(x = x, mean = mean(x), sd = sd(x)), col = "red", lty = 1, lwd = 2, add = TRUE) # ?

发生的事情是最后一个图没有使用

的值
set.seed(1L)
x <- rnorm(n = 1e3L, mean = 200, sd = 30)

mean(x)
#[1] 199.6506
sd(x)
#[1] 31.04748

用于绿色曲线。
来自函数 curve 的文档(我的重点):

The function or expression expr (for curve) or function x (for plot) is evaluated at n points equally spaced over the range [from, to]. The points determined in this way are then plotted.

If either from or to is NULL, it defaults to the corresponding element of xlim if that is not NULL.

What happens when neither from/to nor xlim specifies both x-limits is a complex story. For plot() and for curve(add = FALSE) the defaults are (0, 1). For curve(add = NA) and curve(add = TRUE) the defaults are taken from the x-limits used for the previous plot. (This differs from versions of R prior to 2.14.0.)

以下函数显示了文档中的内容。它输出 min(x)max(x)(x 限制)以及 mean(x)sd(x) 的值,这些值根据传递给函数的向量计算得出。
下面的值 length.out = 101 是默认值 n = 101

xx <- seq(100, 320, length.out = 101)
mean(xx)
#[1] 210
sd(xx)
#[1] 64.46038


f <- function(x) {
  cat("Inside the function:\n")
  cat("min(x):", min(x), "\tmax(x):", max(x), "\n")
  cat("mean(x):", mean(x), "sd(x):", sd(x), "\n")
  dnorm(x, mean = mean(x), sd = sd(x))
}

hist(x, probability = TRUE, ylim = c(0, 0.015))
curve(dnorm(x = x, mean = 200, sd = 30), col = "black", lty = 1, lwd = 2, add = TRUE) # OK
curve(dnorm(x = x, mean = 199.6506, sd = 31.04748), col = "green", lty = 1, lwd = 2, add = TRUE) # OK

cat("Outside the function:\nmin(x):", min(x), "\tmax(x):", max(x), "\n\n")
#Outside the function:
#min(x): 109.7585   max(x): 314.3083 

curve(f(x), col = "red", lty = 1, lwd = 2, add = TRUE) # ?
#Inside the function:
#min(x): 100    max(x): 320 
#mean(x): 210 sd(x): 64.46038 

这些值是预期值,这是记录在案的行为。
最后是剧情。