Matplotlib堆积直方图箱宽度

时间:2016-08-23 13:42:26

标签: python matplotlib

在Matplotlib中创建堆叠直方图时,我注意到bin宽度缩小了。在这个简单的例子中:

import numpy as np
import matplotlib
import matplotlib.pylab as plt

#Create histograms and plots
fig = plt.figure()
gs = matplotlib.gridspec.GridSpec(1, 2)
h1 = fig.add_subplot(gs[0])
h2 = fig.add_subplot(gs[1])

x = np.random.normal(0, 5, 500)
y = np.random.normal(0, 20, 500)

bins = np.arange(-60,60, 5)

h1.hist([x, y], bins=bins, stacked=True)
h2.hist(x, bins=bins, alpha=1)
h2.hist(y, bins=bins, alpha=0.5)

plt.tight_layout()
plt.show()
filename = 'sample.pdf'
plt.savefig(filename)

我得到以下输出:

enter image description here

请注意,左侧的直方图在每个箱子之间都有间距,即使左右两侧的直方图都使用相同的箱子。

有没有办法纠正这种行为?我希望左边的直方图使用完整的bin宽度,以便相邻的bin共享边缘。

1 个答案:

答案 0 :(得分:0)

如果ax.hist - 调用的第一个参数是列表列表(或2d numpy-array或两者的组合),它将自动使bin变小。 rwidth调用的ax.hist参数是确定bin宽度的参数。将其设置为1将执行您希望它执行的操作:

h1.hist([x, y], bins=bins, stacked=True, rwidth=1)

相关问题