Monday, February 22, 2010

Replot the Poisson example with Python


I realized that I used R for the plot of the Poisson distribution from the other day, and I decided to redo it with matplotlib.

This might be a first, since I finally figured out how to set the axis limits. I still have had another problem, I would like to plot the lines after the points, but matplotlib does it how it wants, I guess. It doesn't matter which order the plot and scatter calls are in, the points get plotted last. Maybe I'll ask on SO.

[Those guys know everything: the answer is, you just set the zorder. Here is a link to the example code.]


import math
import matplotlib.pyplot as plt

def poisson(m):
def f(k):
e = math.e**(-m)
f = math.factorial(k)
g = m**k
return g*e/f
return f

R = range(20)
L = list()
means = (1,2,4,10)
for m in means:
f = poisson(m)
L.append([f(k) for k in R])
colors = ['r','g','b','purple']

for c,P in zip(colors,L):
plt.plot(R,P,zorder=1,color='0.2',lw=1.5)
plt.scatter(R,P,zorder=2,s=150,color=c)

ax = plt.axes()
ax.set_xlim(-0.5,20)
ax.set_ylim(-0.01,0.4)
plt.savefig('example.png')

No comments: