Search code examples
rplotprobability-density

Plot Lognormal Probability Density in R


I am trying to generate a plot for Lognormal Probability Density in R, with 3 different means log and standards deviation log. I have tried the following, but my graph is so ugly and does not look good at all.

 x<- seq(0,10,length = 100)
 a <- dlnorm(x, meanlog = 0, sdlog = 1, log = FALSE)
 b <- dlnorm(x, meanlog = 0, sdlog = 1.5, log = FALSE)
 g <- dlnorm(x, meanlog = 1.5, sdlog = 0.2, log = FALSE)
 plot(x,a, lty=5, col="blue", lwd=3)
 lines(x,b, lty=2, col = "red")
 lines(x,g, lty=4, col = "green")

I even was trying to add legend on the right top for each mean log and standard deviation log, but it would not work with me. I was wondering if someone could guide me out with that.

Right top of the graph


Solution

  • There is really nothing wrong in your code. You just forgot to:

    • use type = "l" in plot;
    • set a good ylim to hold all lines.

    Here is a simple solution with matplot:

    matplot(x, cbind(a,b,g), type = "l", ylab = "density", main = "log-normal",
            col = 1:3, lty = 1:3)
    

    To add legend, use

    legend("topright",
           legend = c("mu = 0, sd = 1", "mu = 0, sd = 1.5", "mu = 1.5, sd = 0.2"),
           col = 1:3,
           lty = 1:3)
    

    enter image description here

    You can also read ?plotmath for adding expressions. Try changing the legend argument above to:

    legend = c(expression(ln(y) %~% N(0,1)),
               expression(ln(y) %~% N(0,1.5)),
               expression(ln(y) %~% N(1.5,0.2)))