我使用matplotlib.pyplot创建直方图。我不是在这些直方图的地块兴趣浓厚,但感兴趣的频率和垃圾箱(我知道我可以写我自己的代码来做到这一点,但我们更希望用这个包)。任何方式与matplotlib.pyplot创建直方图,而不绘制直方图?
我知道我能做到以下几点,
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[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()? – Pablo
感谢您的建议。看起来问题在于别的地方。如果我按行(不是函数)运行上面的代码,它可以与np.histogram()和plt.hist()一起使用。关于为什么在函数中使用它的任何想法都不起作用? – user1175720