2013-06-27 52 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()任何使用将投入当前轴的情节 - 这是一个全局变量。