以直方图/ hexplot的形式绘制2D箱中分散值的平均值

时间:2019-11-19 15:44:23

标签: python matplotlib

我有3维分散数据x,y,z。 我想将x和y箱中z的平均值绘制为十六进制图或2D直方图。 有没有matplotlib函数可以做到这一点? 即使这似乎是一个普遍的问题,我也只能提出一些非常麻烦的实现。

例如像这样的东西:

enter image description here

除了颜色应取决于(x,y)bin的平均z值(而不是默认的hexplot / 2D直方图功能中的(x,y)bin的条目数)。

2 个答案:

答案 0 :(得分:2)

@Andrea 的回答非常清楚而且很有帮助,但我想提一个不使用 scipy 库的更快的替代方案

这个想法是做一个由 z 变量加权的 x 和 y 的二维直方图(它具有每个 bin 中 z 变量的总和),然后针对没有权重的直方图进行归一化(它具有每个斌)。这样,您将计算每个 bin 中 z 变量的平均值。

代码:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(0, 10, 10**7)
y = np.random.uniform(10, 20, 10**7)
z = np.exp(-(x-3)**2/5 - (y-18)**2/5) + np.random.random(10**7)

x_bins = np.linspace(0, 10, 50)
y_bins = np.linspace(10, 20, 50)

H, xedges, yedges = np.histogram2d(x, y, bins = [x_bins, y_bins], weights = z)
H_counts, xedges, yedges = np.histogram2d(x, y, bins = [x_bins, y_bins]) 
H = H/H_counts

plt.imshow(H.T, origin='lower',  cmap='RdBu',
            extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
plt.colorbar()

enter image description here

在我的计算机中,此方法比使用 scipy 的 binned_statistic_2d 大约快 5 倍

答案 1 :(得分:1)

如果您要的是分级,则binned_statistic_2d可能对您有用。这是一个示例:

from scipy.stats import binned_statistic_2d
import numpy as np

x = np.random.uniform(0, 10, 1000)
y = np.random.uniform(10, 20, 1000)
z = np.exp(-(x-3)**2/5 - (y-18)**2/5) + np.random.random(1000)

x_bins = np.linspace(0, 10, 10)
y_bins = np.linspace(10, 20, 10)

ret = binned_statistic_2d(x, y, z, statistic=np.mean, bins=[x_bins, y_bins])

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12, 4))
ax0.scatter(x, y, c=z)
ax1.imshow(ret.statistic.T, origin='bottom', extent=(0, 10, 10, 20))

enter image description here