【发布时间】:2013-06-25 06:33:23
【问题描述】:
我正在使用 matplotlib.pyplot 创建直方图。我实际上对这些直方图的图并不感兴趣,但对频率和 bin 感兴趣(我知道我可以编写自己的代码来执行此操作,但更喜欢使用这个包)。
我知道我可以做到以下几点,
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.normal(1.5,1.0)
x2 = np.random.normal(0,1.0)
freq, bins, patches = plt.hist([x1,x1],50,histtype='step')
创建直方图。我只需要freq[0]、freq[1] 和bins[0]。当我尝试使用时出现问题,
freq, bins, patches = plt.hist([x1,x1],50,histtype='step')
在一个函数中。例如,
def func(x, y, Nbins):
freq, bins, patches = plt.hist([x,y],Nbins,histtype='step') # create histogram
bincenters = 0.5*(bins[1:] + bins[:-1]) # center bins
xf= [float(i) for i in freq[0]] # convert integers to float
xf = [float(i) for i in freq[1]]
p = [ (bincenters[j], (1.0 / (xf[j] + yf[j] )) for j in range(Nbins) if (xf[j] + yf[j]) != 0]
Xt = [j for i,j in p] # separate pairs formed in p
Yt = [i for i,j in p]
Y = np.array(Yt) # convert to arrays for later fitting
X = np.array(Xt)
return X, Y # return arrays X and Y
当我调用func(x1,x2,Nbins) 并绘制或打印X 和Y 时,我没有得到预期的曲线/值。我怀疑这与plt.hist 有关,因为我的情节中有一个部分直方图。
【问题讨论】:
-
为什么不使用 np.histogram()?
-
感谢您的建议。看起来问题出在其他地方。如果我逐行运行上面的代码(而不是作为函数),它同时适用于 np.histogram() 和 plt.hist()。关于为什么在函数中使用 this 不起作用的任何想法?
标签: python-2.7 matplotlib histogram