我有三维散乱的数据x,y,z,我想把x和y的回收箱中的z的平均值画成十六进制图或二维直方图图。有什么matplotlib函数可以这样做吗?我只能想出一些非常麻烦的实现,尽管这似乎是一个常见的问题。
例如,类似这样的事情:

但颜色应该取决于(x,y) bin的平均z值(而不是(x,y) bin中的条目数,如默认的h爆炸性/2D直方图函数中的条目数)。
发布于 2019-11-19 16:34:38
如果您想要的是绑定,那么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))

发布于 2021-04-15 08:47:45
@Andrea的回答很清楚,也很有帮助,但我想提一下不使用库的更快的替代方案。
其思想是用z变量加权x和y的2d直方图(在每个bin中有z变量的和),然后在没有权重的情况下对直方图进行规范化(每个bin中有计数数)。这样,您将在每个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()

在我的计算机中,这种方法比使用的binned_statistic_2d大约快5倍。
https://stackoverflow.com/questions/58937863
复制相似问题