2013-06-27 147 views
6

我使用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)和情節或打印XY,我沒有得到我預期的曲線/值。我懷疑它與plt.hist有關,因爲我的情節中存在部分直方圖。

+5

爲什麼你不使用np.histogram()? – Pablo

+0

感謝您的建議。看起來問題在於別的地方。如果我按行(不是函數)運行上面的代碼,它可以與np.histogram()和plt.hist()一起使用。關於爲什麼在函數中使用它的任何想法都不起作用? – user1175720

回答

3

我不知道我是否很好地理解你的問題,但在這裏,你有一個非常簡單的自制直方圖(1D或2D)的例子,每個直方圖在函數內部, :

import numpy as np 
import matplotlib.pyplot as plt 

def func2d(x, y, nbins): 
    histo, xedges, yedges = np.histogram2d(x,y,nbins) 
    plt.plot(x,y,'wo',alpha=0.3) 
    plt.imshow(histo.T, 
       extent=[xedges.min(),xedges.max(),yedges.min(),yedges.max()], 
       origin='lower', 
       interpolation='nearest', 
       cmap=plt.cm.hot) 
    plt.show() 

def func1d(x, nbins): 
    histo, bin_edges = np.histogram(x,nbins) 
    bin_center = 0.5*(bin_edges[1:] + bin_edges[:-1]) 
    plt.step(bin_center,histo,where='mid') 
    plt.show() 

x = np.random.normal(1.5,1.0, (1000,1000)) 

func1d(x[0],40) 
func2d(x[0],x[1],40) 

當然,你可以檢查數據中心是正確的,但我認爲該示例顯示了有關這個話題的一些有用的東西。

我的建議:儘量避免在你的代碼中的任何循環!他們殺了表演。如果你看,在我的例子中沒有循環。 Python中數值問題的最佳做法是避免循環! Numpy有很多C實現的功能,可以完成所有艱難的循環工作。

0

但是你可以繞過pyplot:

import matplotlib.pyplot 

fig = matplotlib.figure.Figure() 
ax = matplotlib.axes.Axes(fig, (0,0,0,0)) 
numeric_results = ax.hist(data) 
del ax, fig 

它不會影響主動軸和人物,所以這將是確定即使在繪製別的東西中間用它。

這是因爲plt.draw_something()任何使用將投入當前軸的情節 - 這是一個全局變量。