Time for action – drawing the lognormal distribution

Let's visualize the lognormal distribution and its PDF with a histogram:

  1. Generate random numbers using the normal() function from the random NumPy module:
    N=10000
    lognormal_values = np.random.lognormal(size=N)
  2. Draw the histogram and theoretical PDF with a center value of 0 and standard deviation of 1:
    _, bins, _ = plt.hist(lognormal_values, np.sqrt(N), normed=True, lw=1)
    sigma = 1
    mu = 0
    x = np.linspace(min(bins), max(bins), len(bins))
    pdf = np.exp(-(numpy.log(x) - mu)**2 / (2 * sigma**2))/ (x * sigma * np.sqrt(2 * np.pi))
    plt.plot(x, pdf,lw=3)
    plt.show()

    The fit of the histogram and theoretical PDF is excellent, as you can see in the following diagram:

What just happened?

We visualized the lognormal ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.