This post illustrates techniques for visualizing statistical distributions using Python and its graphics libraries, particularly Matplotlib. The resulting charts are used in the statistical distributions lesson of the statistics course.
Required Libraries Import
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm, binom, poisson, expon, uniform, bernoulli, chi2, t
Normal distribution
# Normal Distribution
mu = 0 # Mean
sigma = 1 # Standard deviation
x = np.linspace(-5, 5, 1000)
plt.plot(x, norm.pdf(x, mu, sigma), label='Normal Distribution')
plt.title('Normal Distribution')
plt.xlabel('Value')
plt.ylabel('Probability Density')
plt.legend()
plt.show()
Exponential distribution
# Exponential Distribution
lam = 1 # Decay rate
x = np.linspace(0, 5, 1000)
plt.plot(x, expon.pdf(x, scale=1/lam), label='Exponential Distribution')
plt.title('Exponential Distribution')
plt.xlabel('Time')
plt.ylabel('Probability Density')
plt.legend()
plt.show()
Bernoulli distribution
# Parameter of the Bernoulli distribution
p = 0.4 # Probability of success (1)
# Possible values of the Bernoulli random variable
x = [0, 1]
# Calculation of probability mass function
pmf_values = bernoulli.pmf(x, p)
# Creating the plot
bar_width = 0.3
x_pos = np.array([0, 0.6]) # Adjust these values to change the spacing
plt.bar(x_pos, pmf_values, width=bar_width, color='blue', alpha=0.7, label='Bernoulli Distribution')
# Setting labels and title
plt.title(f'Bernoulli Distribution (p = {p:.2f})')
plt.xlabel('Value')
plt.ylabel('Probability Mass')
plt.xticks(x_pos, ['0', '1']) # Set x-ticks at bar positions
plt.legend()
plt.grid(True, axis='y', linestyle='--', alpha=0.7) # Adds horizontal grid to improve readability
# Set x-axis limits to focus on the bars
plt.xlim(-0.2, 0.8)
plt.show()
Binomial distribution
# Binomial Distribution
n = 4 # Number of trials
p = 0.5 # Probability of success
x = np.arange(0, n+1)
# Calculate PMF
pmf_values = binom.pmf(x, n, p)
# Create the plot
bar_width = 0.8
plt.bar(x, pmf_values, width=bar_width, color='blue', alpha=0.7, label='Binomial Distribution')
# Set labels and title
plt.title(f'Binomial Distribution (n={n}, p={p})')
plt.xlabel('Number of Successes')
plt.ylabel('Probability')
# Set x-ticks to integers
plt.xticks(x)
# Add legend and grid
plt.legend()
plt.grid(True, axis='y', linestyle='--', alpha=0.7)
# Adjust x-axis limits for better appearance
plt.xlim(-0.5, n+0.5)
plt.show()
Poisson distribution
# Poisson Distribution
lam = 5 # Rate or mean number of events
x = np.arange(0, 20)
# Calculate PMF
pmf_values = poisson.pmf(x, lam)
# Create the plot
bar_width = 0.8
plt.bar(x, pmf_values, width=bar_width, color='blue', alpha=0.7, label='Poisson Distribution')
# Set labels and title
plt.title(f'Poisson Distribution (λ = {lam})')
plt.xlabel('Number of Events')
plt.ylabel('Probability')
# Set x-ticks
plt.xticks(np.arange(0, 20, 2)) # Set x-ticks every 2 units for better readability
# Add legend and grid
plt.legend()
plt.grid(True, axis='y', linestyle='--', alpha=0.7)
# Adjust x-axis limits for better appearance
plt.xlim(-0.5, 19.5)
plt.show()
Uniform distribution
# Uniform Distribution
a = 0 # Lower bound
b = 10 # Upper bound
# Generate x values
x = np.linspace(a-1, b+1, 1000)
# Calculate PDF
pdf_values = uniform.pdf(x, loc=a, scale=b-a)
# Create the plot
plt.figure(figsize=(10, 6))
plt.plot(x, pdf_values, color='blue', linewidth=2, label='Uniform Distribution')
# Fill the area under the curve within the bounds
plt.fill_between(x, pdf_values, where=((x >= a) & (x <= b)), color='blue', alpha=0.3)
# Set labels and title
plt.title(f'Uniform Distribution (a={a}, b={b})')
plt.xlabel('Value')
plt.ylabel('Probability Density')
# Add legend and grid
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)
# Set axis limits
plt.xlim(a-1, b+1)
plt.ylim(0, uniform.pdf(a, loc=a, scale=b-a) * 1.1)
# Add vertical lines at bounds
plt.axvline(x=a, color='gray', linestyle='--')
plt.axvline(x=b, color='gray', linestyle='--')
plt.show()
Chi square distribution
# Set range for degrees of freedom
degrees_of_freedom = range(1, 11)
# Create a range of x values for plotting
x = np.linspace(0, 20, 1000)
# Plot chi-squared distributions for each degree of freedom
plt.figure(figsize=(10, 6))
for k in degrees_of_freedom:
plt.plot(x, chi2.pdf(x, k), label=f'df = {k}')
plt.title('Chi-Squared Distributions for Degrees of Freedom from 1 to 10')
plt.xlabel('Value')
plt.ylabel('Probability Density')
plt.legend(title='Degrees of Freedom')
plt.grid(True)
plt.show()
t distribution vs normal distribution
# Set up a range for x values to cover enough area for both distributions
x_range = np.linspace(-5, 5, 1000)
# Compute the probability density functions for a t-distribution with 10 degrees of freedom and a normal distribution
t_distribution = t.pdf(x_range, df=10)
normal_distribution = norm.pdf(x_range)
# Plot both distributions for comparison
plt.figure(figsize=(10, 6))
plt.plot(x_range, t_distribution, label='Student\\'s t-distribution, df=10')
plt.plot(x_range, normal_distribution, label='Normal distribution')
plt.title('Comparison of Student\\'s t-Distribution and Normal Distribution')
plt.xlabel('Value')
plt.ylabel('Probability Density')
plt.legend()
plt.grid(True)
plt.show()
Sigmoid function
# Define the sigmoid function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Set up a range for x values to display the sigmoid curve
x_values = np.linspace(-10, 10, 400)
# Compute the sigmoid function for these x values
sigmoid_values = sigmoid(x_values)
# Plot the sigmoid function
plt.figure(figsize=(10, 6))
plt.plot(x_values, sigmoid_values, label='Sigmoid Function', color='blue')
plt.title('Sigmoid Function')
plt.xlabel('x')
plt.ylabel('S(x)')
plt.grid(True)
plt.ylim(-0.1, 1.1) # Extend y-axis to show the asymptotic behavior clearly
plt.axhline(y=0, color='black',linewidth=0.5)
plt.axhline(y=1, color='black',linewidth=0.5)
plt.axvline(x=0, color='black',linewidth=0.5)
plt.show()
