Search code examples
rplotmeannormal-distributionvariance

how to plot normal distribution with the same mean but different variance in r


I tried to plot 6 normal distribution figure to display the effect of mean and variance on such a plot,my code is as follow:

    par(mfrow=c(3,2),bty = "n")     # 3 rows by 2 columns, turn off border
    mu <- c(6, 8, 6, 8, 6, 8)       #designate the 6 mean values
    sigma <- c(3, 3, 2, 2, 1, 1)        #designate the 6 sd values
    label <- c("(a)","(b)","(c)","(d)","(e)","(f)") #designate the 6 labels of the 6 figures
    for(i in 1:length(mu))          
    {
     mu.r <- mu[i]          
     sigma.r <- sigma[i]        
     lab.r <- label[i]      
     x <- seq((mu.r - 4*sigma.r), (mu.r + 4*sigma.r), len = 200)
    #designate the starting and ending value of mean
     plot(x, dnorm(x, mean = mu.r, sd = sigma.r),axes = F,
         type="l",lwd = 2, xlab = lab.r, ylab = "",
              main=paste0('mu=',mu.r,', sigma=',sigma.r),
           )
    axis(1, at = (mu.r - 4*sigma.r) : (mu.r + 4*sigma.r))
    abline(v = mu.r, col = "red", lwd = 2.5, lty = "longdash")
         
    }
    the figures generated is as follow:
   [enter image description here][1]


  [1]: https://i.sstatic.net/Z4czh.png

Solution

  • You didin't said what exactly was the problem. I assume is that all your graphs look the same. That happens because you set your x axis depending on the variance, you need to leave all the graphs on the same scale in order to compare them. I simply set a arbitrary interval of 7 around the mean:

    for(i in 1:length(mu))          
    {
      mu.r <- mu[i]          
      sigma.r <- sigma[i]        
      lab.r <- label[i]      
      x <- (mu.r - 7):(mu.r + 7)
      #designate the starting and ending value of mean
      plot(x, dnorm(x, mean = mu.r, sd = sigma.r),axes = F,
           type="l",lwd = 2, xlab = lab.r, ylab = "",
           main=paste0('mu=',mu.r,', sigma=',sigma.r),
      )
      axis(1, at = x)
      abline(v = mu.r, col = "red", lwd = 2.5, lty = "longdash")
      
    }
    

    Output:

    enter image description here