Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: plotting a histogram with a function line on top

I'm trying to do a little bit of distribution plotting and fitting in Python using SciPy for stats and matplotlib for the plotting. I'm having good luck with some things like creating a histogram:

seed(2)
alpha=5
loc=100
beta=22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = hist(data, 100, normed=True)

enter image description here

Brilliant!

I can even take the same gamma parameters and plot the line function of the probability distribution function (after some googling):

rv = ss.gamma(5,100,22)
x = np.linspace(0,600)
h = plt.plot(x, rv.pdf(x))

enter image description here

How would I go about plotting the histogram myHist with the PDF line h superimposed on top of the histogram? I'm hoping this is trivial, but I have been unable to figure it out.

like image 620
JD Long Avatar asked Jul 03 '12 16:07

JD Long


People also ask

How do you fit a curve to a histogram in Python?

Just find the mean and the standard deviation, and plug them into the formula for the normal (aka Gaussian) distribution (en.wikipedia.org/wiki/Normal_distribution). The mean of a histogram is sum( value*frequency for value,frequency in h )/sum( frequency for _,frequency in h ) .


1 Answers

just put both pieces together.

import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
alpha, loc, beta=5, 100, 22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = plt.hist(data, 100, normed=True)
rv = ss.gamma(alpha,loc,beta)
x = np.linspace(0,600) 
h = plt.plot(x, rv.pdf(x), lw=2)
plt.show()

enter image description here

to make sure you get what you want in any specific plot instance, try to create a figure object first

import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
# setting up the axes
fig = plt.figure(figsize=(8,8))
ax  = fig.add_subplot(111)
# now plot
alpha, loc, beta=5, 100, 22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = ax.hist(data, 100, normed=True)
rv = ss.gamma(alpha,loc,beta)
x = np.linspace(0,600)
h = ax.plot(x, rv.pdf(x), lw=2)
# show
plt.show()
like image 179
nye17 Avatar answered Sep 20 '22 14:09

nye17