Plot Normal Distribution Density in R

The mathematical formula for the normal distribution density has two parameters: $\mu, \sigma$: $$p(x)=\frac{1}{\sqrt{2\pi}\cdot\sigma}e^{-\frac{1}{2}\cdot(\frac{x-\mu}{\sigma})^2}$$ where $\mu$ is the mean of the distribution and $\sigma$ is the standard deviation.
In order to plot the graph, we use the following way:
  • Divide x-axis into small intervals, with width denoted $\Delta x$.
  • The integral of the normal density is approximated by summing the masses of all the tiny intervals.
Note that we illustrate $\mu\pm3\sigma$ in the graph, which means its area will be approximately equal to 0.997.

R code:






Furthermore, we can plot the density graph of a given function. For instance, $p(x)=6x(1-x)$ over the interval $x\in[0,1]$. It is easy to calculate the integral: $$\int_{x=0}^{1}p(x)dx=6\cdot\int_{x=0}^{1}(x-x^2)dx=6\cdot(\frac{1}{2}x^2-\frac{1}{3}x^3)\Big|_{0}^{1}=1$$
R code:





Reference:
Kruschke, J., K. (2010). Doing Bayesian Data Analysis: A Tutorial with R and BUGS. Chapter 3.


没有评论:

发表评论