Using R To Plot The Probability Density Function
Using R To Plot The Probability Density Function
a. f(x) is positive everywhere in the supporting base B, that is f(x)>0 for all x
in B
b. The area under the curve f(x) in the base support B is 1, i.e. ∫ b. f ( x)dx = 1
c. If f(x) is the PDF of x, then the probability that x belongs to A, where A is
some interval within the range, is given by the integral of f(x) over that
interval, i.e.
P ( X ∈ A) = ∫ A. f ( x) dx
Now, let’s see how we can use R language to plot a density function
Define a vector x over the domain. We can then apply the distribution’s
density function to x and then plot the result. The code sniper plots the
standard normal distribution:
> x<-seq(from=-3,to=+3,length.out=100)
> plot(x,dnorm(x))
>
1
Whilst,
> x<-seq(from=-3,to=+3,length.out=1000)
> plot(x,dnorm(x))
>
If the first argument of the density function is a vector, then the function
calculates the density at each point and returns the vector of densities.
x<-seq(from=-3,to=+3,length.out=1000)
> plot(x,dnorm(x))
>
> x<-seq(from=0,to=6,length.out=100) # Define the density domain
> ylim<-c(0,0.6)
>
> par(mfrow=c(2,2)) # Create a 2x2 plotting area
>
> plot(x,dunif(x,min=2,max=4),main="Uniform",type="l",ylim=ylim) #Plot a uniform density
>
> plot(x,dnorm(x,mean=3,sd=1),main="Normal",type="l",ylim=ylim) #Plot a Normal density
>
>plot(x,dexp(x,rate=1/2),main="Exponential",type="l",ylim=ylim) #Plot an Exponential density
>
> plot(x,dgamma(x,shape=2,rate=1),main="Gamma",type="l",ylim=ylim) #Plot a Gamma
density
>
2
3