Tuesday, June 14, 2022

Plotting normal distribution curve along with central limit theorem in matplotlib

 Для правильного построения плота необходимо правильно нормализовать второй график с помощью density=True, stacked=True

(.env) boris@boris-All-Series:~/VOTING$ cat plotCurvesWithCLT.py

import numpy as np

import matplotlib.pyplot as plt

import scipy.stats as stats

# 1000 simulations of die roll

n = 10000

avg = []

for i in range(1,n):

    a = np.random.randint(1,7,10)

    avg.append(np.average(a))

# Normalise this histogram too

plt.hist(avg[0:], 20, density=True, stacked=True)

zscore = stats.zscore(avg[0:])

mu, sigma = np.mean(avg), np.std(avg)

s = np.random.normal(mu, sigma, 10000)

# Create the bins and histogram

count, bins, ignored = plt.hist(s, 20, density=True, stacked=True) 

# Use scipy.stats implementation of the normal pdf

# Plot the distribution curve

x = np.linspace(1.5, 5.5, num=100)

plt.plot(x, stats.norm.pdf(x, mu, sigma))

plt.show()






























Второй вариант

(.env) boris@boris-All-Series:~/VOTING$ cat plotCurvesWithCLT3.py
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats

# 1000 simulations of die roll
n = 10000

avg = []
for i in range(1,n):
    a = np.random.randint(1,7,10)
    avg.append(np.average(a))

# Normalise this histogram too
plt.hist(avg[0:], 20, density=True, stacked=True)

mu, sigma = np.mean(avg), np.std(avg)
s = np.random.normal(mu, sigma, 10000)

# Create the bins and histogram
count, bins, ignored = plt.hist(s, 20, density=True, stacked=True) 
x = np.linspace(bins.min(), bins.max(), num=100)

###################################
# Find pdf of normal kernel at mu
###################################
max_density = stats.norm.pdf(mu, mu, sigma)

################################
# Calculate how to scale pdf
################################
scale = count.max() / max_density
plt.plot(x, scale * stats.norm.pdf(x, mu, sigma))
plt.show()





Plotting 3 Histograms normalised












































No comments:

Post a Comment