您可以在绘图之前计算要在分箱二维图中显示的值,然后显示为imshow 图。
如果您乐于使用 pandas,一种选择是根据剪切 (pandas.cut) x 和 y 数据对 z 数据进行分组。然后应用平均值 (.mean()) 并 unstack 以获得数据透视表。
df.z.groupby([pd.cut(x, bins=xbins), pd.cut(y, bins=ybins)]) \
.mean().unstack(fill_value=0)
这是一个完整的例子:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors
x = np.arange(1,8)
y = np.arange(1,6)
X,Y = np.meshgrid(x,y)
df = pd.DataFrame({"x":X.flatten(), "y":Y.flatten(), "z":(X*Y).flatten()})
xbins = [0,4,8]
ybins = [0,3,6]
hist = df.z.groupby([pd.cut(df.x, bins=xbins), pd.cut(df.y, bins=ybins)]) \
.mean().unstack(fill_value=0)
print hist
im = plt.imshow(hist.values, norm=matplotlib.colors.LogNorm(1,100))
plt.xticks(range(len(hist.index)), hist.index)
plt.yticks(range(len(hist.columns)), hist.columns)
plt.colorbar(im)
plt.show()
必须手动创建对数范数,并且需要根据分箱标记刻度。