我使用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