问题描述
我正在使用pyplot.hist2d绘制由第三个变量z加权的2D直方图(x与y)。我不想像hist2d那样将给定像素[x_i,y_i]中的z值求和,而是想获得落入该像素的所有数据点的平均z。
谢谢。
解决方法
Numpy的histogram2d()
可以将两个计数(标准直方图)都计算为和(通过weights
参数)。两者相除得出平均值。
下面的示例显示了3个直方图和一个色条。选择的样本数量相对较小,以说明计数为零的单元格会发生什么情况(除法给出NaN
,因此该单元格保留为空白)。
import numpy as np
import matplotlib.pyplot as plt
N = 1000
x = np.random.uniform(0,10,N)
y = np.random.uniform(0,N)
z = np.cos(x) * np.sin(y)
counts,xbins,ybins = np.histogram2d(x,y,bins=(30,20))
sums,_,_ = np.histogram2d(x,weights=z,bins=(xbins,ybins))
fig,(ax1,ax2,ax3) = plt.subplots(ncols=3,figsize=(15,4))
m1 = ax1.pcolormesh(ybins,counts,cmap='coolwarm')
plt.colorbar(m1,ax=ax1)
ax1.set_title('counts')
m2 = ax2.pcolormesh(ybins,sums,cmap='coolwarm')
plt.colorbar(m2,ax=ax2)
ax2.set_title('sums')
with np.errstate(divide='ignore',invalid='ignore'): # suppress possible divide-by-zero warnings
m3 = ax3.pcolormesh(ybins,sums / counts,cmap='coolwarm')
plt.colorbar(m3,ax=ax3)
ax3.set_title('mean values')
plt.tight_layout()
plt.show()