如何通过设置最小计数阈值降低NumPy二维直方图的噪声?
过滤二维直方图中数据量不足的Bin消除噪声
解决方法很直接:利用np.histogram2d返回的counts数组(记录每个bin的样本数量),把样本数少于5的bin对应的加权均值设为NaN,matplotlib绘图时会自动忽略这些NaN区域,从而过滤掉噪声。
修改后的完整代码如下:
import numpy as np import matplotlib.pyplot as plt n = 10000 x1 = np.random.randn(n) y1 = x1 + np.random.randn(n) z1 = np.random.randn(n) bins = 40 fig, axs = plt.subplots(1, 1, figsize=(10, 10), constrained_layout=True) sums, xbins, ybins = np.histogram2d(x1, y1, bins=bins, weights=z1) counts, _, _ = np.histogram2d(x1, y1, bins=bins) # 核心过滤步骤:样本数少于5的bin设为NaN with np.errstate(divide='ignore', invalid='ignore'): weighted_mean = sums / counts filtered_mean = np.where(counts >= 5, weighted_mean, np.nan) # 使用过滤后的数组绘图 img = axs.pcolormesh(xbins, ybins, filtered_mean, cmap='inferno') fig.colorbar(img, ax=axs, label='z') axs.set(xlabel='x', ylabel='y', title='Weighed by z (filtered bins with <5 samples)') fig.show()
关键说明
np.where(counts >=5, weighted_mean, np.nan):对每个bin做条件判断,只有样本数≥5的bin保留计算出的加权均值,其余替换为NaN。- 保留
np.errstate(divide='ignore', invalid='ignore')是为了避免计算sums/counts时出现除以0的警告(样本数为0的bin会触发)。 - 处理后,原本噪声密集的边缘区域会被隐藏,只保留数据量足够的有效区域,直方图的可读性会大幅提升。
内容的提问来源于stack exchange,提问作者Cumulus303
相关产品推荐
相关产品推荐

