john chong
john chong

Reputation: 25

How to plot the Poisson distribution graph with Python?

import numpy as np
from scipy.stats import poisson
import matplotlib.pyplot as plt

#generate Poisson distribution with sample size 30000
x = poisson.rvs(mu=0.9, size=30000)


#create plot of Poisson distribution
plt.hist(x, density=True, edgecolor='black',bins=7,align='left')


fig, ax = plt.subplots(1, 1)
mu = 0.9
mean, var, skew, kurt = poisson.stats(mu, moments='mvsk')
x = np.arange(poisson.ppf(0.01, mu),
              poisson.ppf(0.99, mu))
ax.plot(x, poisson.pmf(x, mu), 'red', ms=8, label='poisson pmf')

I use this code to draw two different graphs but it is not the outcome I expected.How can I modify my code to make the graph like the scatter point with the histogram.Thx!

The question is - plot the histogram using sample points generated above (set density = True, also adjust the number of bins to make the graph look nicer). Compare the results with the scatter plot using the Poison distribution formula directly.

Upvotes: 2

Views: 2491

Answers (1)

Salvatore Daniele Bianco
Salvatore Daniele Bianco

Reputation: 2701

I think this is what you need:

import numpy as np
from scipy.stats import poisson
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)

#define mu
mu = 0.9
mean, var, skew, kurt = poisson.stats(mu, moments='mvsk')

#generate Poisson distribution with sample size 30000
x_sampled = poisson.rvs(mu=mu, size=300000)

#define bins as {0, 1, ..., max(x), max(x)+1}
bins = np.arange(x_sampled.max()+2)

#using the bins to compute the density of sampled data
density , _ = np.histogram(x_sampled, bins-.5, density=True)

#plotting the samples density
plt.scatter(bins[:-1], density, label="sampled data")

#plotting the actual density
ax.plot(bins[:-1], poisson.pmf(bins[:-1], mu), 'red', ms=8, label='poisson pmf')

plt.legend()
plt.show()

output:

enter image description here

Upvotes: 1

Related Questions