Python 2.7 使用matplotlib.pyplot创建直方图而不打印直方图的任何方法?
我正在使用matplotlib.pyplot创建直方图。实际上,我对这些直方图的绘图不感兴趣,但对频率和容器感兴趣(我知道我可以编写自己的代码来实现这一点,但更愿意使用这个包) 我知道我可以做到以下几点Python 2.7 使用matplotlib.pyplot创建直方图而不打印直方图的任何方法?,python-2.7,matplotlib,histogram,Python 2.7,Matplotlib,Histogram,我正在使用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,
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[0]
,freq[1]
和bin[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
有关,因为我的绘图中有一个部分直方图。我不知道我是否非常理解你的问题,但这里有一个非常简单的自制直方图示例(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实现的函数,可以完成所有硬循环工作。否
但您可以绕过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()
都会将绘图放在当前轴上-这是一个全局变量。如果您只想计算直方图(即,计算给定箱子中的点数)而不显示它,则可以使用np.histogram()函数(用于二维直方图)或(对于1D柱状图):
输出形式将与
plt.hist
和plt.hist2d
相同,唯一的区别是没有绘图为什么不使用np.histogram()?感谢您的建议。问题似乎出在其他地方。如果我逐行运行上面的代码(不是作为函数),它可以同时使用np.histogram()和plt.hist()。关于为什么在函数中使用它不起作用,有什么想法吗?
hst = np.histogram(A, bins)
hst2d = np.histogram2d(X,Y,bins)