Matplotlib Pyplot Bar 缺失数据(别名)

问题描述 投票:0回答:1

我最近在使用 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]

#Get some high-density data
raw=np.abs(np.random.normal(10000,1000,2000000).astype(np.int16))
counts=np.bincount(raw)
bins=np.arange(len(counts))


#Three different ways to plot the histogram
ax1.bar(bins, counts)
ax2.bar(bins, counts, width=1)
ax3.fill_between(bins, counts, step='mid') #Setting step='mid' centres the bars on the data


#Tidy up and plot
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') #vector graphics means all data is represented in the image
plt.show()

matplotlib pyplot 条显示锯齿

经过一番挖掘,我找到了可能的解决方案,并将自行回答这个问题。

我希望有一些准确的方式来显示数据。

matplotlib bar-chart histogram
1个回答
0
投票

这是一个混叠问题,因为代表它们的数据点多于像素。由于空白,它变得特别明显。通过为 bar() 的“宽度”参数设置适当的值,可以使图看起来更漂亮,这样条形之间就没有空格。这里我使用width=1(默认是0.8)。下面的代码在我的中型笔记本电脑上运行大约需要 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]

#Get some high-density data
raw=np.abs(np.random.normal(10000,1000,2000000).astype(np.int16))
counts=np.bincount(raw)
bins=np.arange(len(counts))


#Three different ways to plot the histogram
ax1.bar(bins, counts)
ax2.bar(bins, counts, width=1)
ax3.fill_between(bins, counts, step='mid') #Setting step='mid' centres the bars on the data


#Tidy up and plot
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')
plt.savefig("norm.svg",format='svg') #vector graphics means all data is represented in the image
plt.show()

matplotlib pyplot 图像别名

人们可能想要传递给 plyplot.bar 的其他关键字参数是

linewidth=0

edgecolor=None
以确保在条形上不绘制边缘。
另一种方法是使用不同的绘图工具,例如 plt.fill_ Between 或 plt.step 或 plt.stairs。我选择使用 fill_ Between 因为其他两个选项使得填充条形变得困难。

请注意,即使我们使空白锯齿消失,我们仍然存在数据点多于代表它们的像素的问题。人们应该研究如何呈现这一点 - 如果对值进行平均,这将平滑数据并隐藏您可能试图捕获的波动。

© www.soinside.com 2019 - 2024. All rights reserved.