python:在顶部绘制带有函数线的直方图 [英] python: plotting a histogram with a function line on top
问题描述
我正在尝试使用 SciPy 进行统计数据和 matplotlib 进行绘图,在 Python 中进行一些分布绘图和拟合.我在创建直方图等方面很幸运:
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)
太棒了!
我什至可以采用相同的 gamma 参数并绘制概率分布函数的线函数(经过一些谷歌搜索):
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))
我将如何使用叠加在直方图顶部的 PDF 行 h
绘制直方图 myHist
?我希望这是微不足道的,但我一直无法弄清楚.
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.
推荐答案
只需将两部分放在一起即可.
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()
为了确保你在任何特定的绘图实例中得到你想要的东西,首先尝试创建一个 figure
对象
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()
这篇关于python:在顶部绘制带有函数线的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!