Edgar Alarcón
Edgar Alarcón

Reputation: 156

Plot a normal distribution in R with specific parameters

I'd like to plot something like this:

plot(dnorm(mean=2),from=-3,to=3)

But it doesn't work as if you do:

plot(dnorm,from=-3,to=3)

what is the problem?

Upvotes: 2

Views: 3030

Answers (2)

Ian Campbell
Ian Campbell

Reputation: 24878

The answer you received from @r2evans is excellent. You might also want to consider learning ggplot, as in the long run it will likely make your life much easier. In that case, you can use stat_function which will plot the results of an arbitrary function along a grid of the x variable. It accepts arguments to the function as a list.

library(ggplot2)
ggplot(data = data.frame(x=c(-3,3)), aes(x = x)) + 
  stat_function(fun = dnorm, args = list(mean = 2))

enter image description here

Upvotes: 5

r2evans
r2evans

Reputation: 161007

curve(dnorm(x, mean = 2), from = -3, to = 3)

normal plot

The curve function looks for the xname= variable (defaults to x) in the function call, so in dnorm(x, mean=2), it is not referencing an x in the calling environment, it is a placeholder for curve to use for iterated values.

The reason plot(dnorm, ...) works as it does is because there exists graphics::plot.function, since dnorm in that case is a function. When you try plot(dnorm(mean=2)), the dnorm(mean=2) is no longer a function, it is a call ... that happens to fail because it requires x (its first argument) be provided.

Incidentally, plot.function calls curve(...), so other than being a convenience function, there is very little reason to use plot(dnorm, ...) over curve(dnorm(x), ...) other than perhaps a little code-golf. The biggest advantage to curve is that it lets you control arbitrary arguments to the dnorm() function, whereas plot.function does not.

Upvotes: 4

Related Questions