以直方图/hexplot的形式绘制2D箱中分散值的平均值 [英] Plot average of scattered values in 2D bins as a histogram/hexplot
问题描述
我有3维分散数据x,y,z.我想将 x 和 y 的 bin 中 z 的平均值绘制为十六进制图或二维直方图.是否有任何 matplotlib 函数可以做到这一点?即使这似乎是一个普遍的问题,我也只能提出一些非常麻烦的实现.
I have 3 dimensional scattered data x, y, z. I want to plot the average of z in bins of x and y as a hex plot or 2D histogram plot. Is there any matplotlib function to do this? I can only come up with some very cumbersome implementations even though this seems to be a common problem.
例如像这样的东西:
除了颜色应取决于 (x, y) bin 的平均 z 值(而不是默认的 hexplot/2D 直方图功能中的 (x, y) bin 中的条目数).>
Except that the color should depend on the average z values for the (x, y) bin (rather than the number of entries in the (x, y) bin as in the default hexplot/2D histogram functionalities).
推荐答案
如果 binning 是您的要求,那么 binned_statistic_2d
可能适合您.举个例子:
If binning is what you are asking, then binned_statistic_2d
might work for you. Here's an example:
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))
这篇关于以直方图/hexplot的形式绘制2D箱中分散值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!