有没有使用matplotlib.pyplot创建直方图而无需绘制直方图的方法?

use*_*720 7 matplotlib histogram python-2.7

我正在使用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')
Run Code Online (Sandbox Code Playgroud)

创建直方图.所有我需要的是freq[0],freq[1]和bins[0].我尝试使用时出现问题,

freq, bins, patches = plt.hist([x1,x1],50,histtype='step')
Run Code Online (Sandbox Code Playgroud)

在一个功能.例如,

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
Run Code Online (Sandbox Code Playgroud)

当我打电话func(x1,x2,Nbins)和情节或打印X和Y,我没有得到我预期的曲线/值.我怀疑它与之相关plt.hist,因为我的情节中有一个部分直方图.

小智 6

您可以使用np.histogram2d(对于 2D 直方图)或np.histogram(对于 1D 直方图):

hst = np.histogram(A, bins)
hst2d = np.histogram2d(X,Y,bins)
Run Code Online (Sandbox Code Playgroud)

plt.hist输出形式将与和相同plt.hist2d,唯一的区别是没有情节。


Pab*_*blo 5

我不知道我是否很好地理解了您的问题,但是在这里,您有一个非常简单的自制直方图示例(一维或二维),每个直方图都在一个函数中,并正确调用:

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)
Run Code Online (Sandbox Code Playgroud)

当然,您可以检查数据的居中是否正确,但我认为该示例显示了有关此主题的一些有用信息。

我的建议:尽量避免代码中出现任何循环!他们扼杀了表演。如果你看,在我的例子中没有循环。python数值问题的最佳实践是避免循环!Numpy 有很多 C 实现的函数来完成所有的硬循环工作。