Plot looks different everytime i run the code

Advertisements

I have a problem with my code. It looks different everytime i run it. Any ideas? I don’t see any problem. I am looking at this code since 2h and I can’t find the problem…

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


x = np.arange(0,24, 1)
y = stats.poisson.pmf(x, mu=13)
a =stats.poisson.rvs(mu=13, size=5000)

#plt.stem(a,x)
plt.hist(a,bins=x,density=True,edgecolor="red")
plt.title("Poisson Verteilung mit Erwartungswert 13")
plt.xlabel("Anzahl M.")
plt.ylabel("Wahrscheinlichkeit")
"""
i=10
o=30
while i != o:
  if y[i]*100<0.5:
    #print(i)
    break
  i+=1
"""

#plot to specific x value
plt.xlim(0, 23)

plt.plot()
plt.plot(13, y[13], marker='x', markersize=5, color="black",label="Varianz")
plt.plot(13, y[13], marker='x', markersize=5, color="black",label="Median")
plt.legend(loc="upper left")

>Solution :

You are using random statistical distribution, each time you run your code a new random distribution is created.
In order to get repeatability (your code picks always the same random distribution when you run it) you have to set a seed at the beginning of your code:

np.random.seed(42)

You can choose which seed you prefer, 42 is a common one.

Complete Code

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


np.random.seed(42)
x = np.arange(0,24, 1)
y = stats.poisson.pmf(x, mu=13)
a =stats.poisson.rvs(mu=13, size=5000)

#plt.stem(a,x)
plt.hist(a,bins=x,density=True,edgecolor="red")
plt.title("Poisson Verteilung mit Erwartungswert 13")
plt.xlabel("Anzahl M.")
plt.ylabel("Wahrscheinlichkeit")
"""
i=10
o=30
while i != o:
  if y[i]*100<0.5:
    #print(i)
    break
  i+=1
"""

#plot to specific x value
plt.xlim(0, 23)

plt.plot()
plt.plot(13, y[13], marker='x', markersize=5, color="black",label="Varianz")
plt.plot(13, y[13], marker='x', markersize=5, color="black",label="Median")
plt.legend(loc="upper left")

plt.show()

Plot

Leave a ReplyCancel reply