You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib Pyplot绘制高密度柱状图出现混叠(数据缺失假象)问题

解决Matplotlib绘制高密度数据时的bar函数混叠问题

我在使用Matplotlib Pyplot的bar函数绘制高密度数据时遇到了混叠问题——实际存在的数据在图表中呈现出缺失块的假象。以下测试代码在中等配置笔记本上运行耗时约40秒:

import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1,3)
ax1 = axes[0]
ax2 = axes[1]
ax3 = axes[2]

# 获取高密度数据
raw=np.abs(np.random.normal(10000,1000,2000000).astype(np.int16))
counts=np.bincount(raw)
bins=np.arange(len(counts))

# 三种不同的直方图绘制方式
ax1.bar(bins, counts)
ax2.bar(bins, counts, width=1)
ax3.fill_between(bins, counts, step='mid') # 设置step='mid'让条形居中对齐数据

# 整理并展示图表
ax3.set_ylim(bottom=0)
for ax in axes: ax.set_xlim(5000, 15000)
ax1.set_title("plt.bar")
ax2.set_title("plt.bar, width=1")
ax3.set_title("plt.fill_between, step='mid'")
fig.tight_layout()
plt.savefig('norm.png', dpi=600)
plt.savefig("norm.svg",format='svg') # 矢量图能完整呈现所有数据
plt.show()

有效解决方案总结

  • 调整bar宽度:将bar函数的width参数设为1,消除条形间隙,避免视觉上的缺失块假象,但高密度数据下渲染速度较慢。
  • 使用fill_between替代:fill_between(bins, counts, step='mid')的渲染效率更高,且能精准对齐数据点,彻底解决混叠问题。
  • 改用专业直方图函数:使用plt.hist()替代手动分箱+bar绘制,该函数针对直方图场景做了优化,处理高密度数据更高效。
  • 输出矢量格式:保存为SVG等矢量图像,确保所有数据细节都能完整保留,不会因位图的像素限制丢失信息。

内容的提问来源于stack exchange,提问作者Harvey Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:41:04