You can use the lognorm() function from the SciPy library in Python to generate a random variable that follows a log-normal distribution.
The following examples show how to use this function in practice.
How to Generate a Log-Normal Distribution
You can use the following code to generate a random variable that follows a log-normal distribution with μ = 1 and σ = 1:
import math
import numpy as np
from scipy.stats import lognorm
#make this example reproducible
np.random.seed(1)
#generate log-normal distributed random variable with 1000 values
lognorm_values = lognorm.rvs(s=1, scale=math.exp(1), size=1000)
#view first five values
lognorm_values[:5]
array([13.79554017, 1.47438888, 1.60292205, 0.92963 , 6.45856805])
Note that within the lognorm.rvs() function, s is the standard deviation and the value inside math.exp() is the mean for the log-normal distribution that you’d like to generate.
In this example, we defined the mean to be 1 and the standard deviation to also be 1.
How to Plot a Log-Normal Distribution
We can use the following code to create a histogram of the values for the log-normally distributed random variable we created in the previous example:
import matplotlib.pyplot as plt #create histogram plt.hist(lognorm_values, density=True, edgecolor='black')
Matplotlib uses 10 bins in histograms by default, but we can easily increase this number using the bins argument.
For example, we can increase the number of bins to 20:
import matplotlib.pyplot as plt #create histogram plt.hist(lognorm_values, density=True, edgecolor='black', bins=20)
The greater the number of bins, the more narrow the bars will be in the histogram.
Related: Three Ways to Adjust Bin Size in Matplotlib Histograms
Additional Resources
The following tutorials explain how to work with other probability distributions in Python:
How to Use the Poisson Distribution in Python
How to Use the Exponential Distribution in Python
How to Use the Uniform Distribution in Python