【问题标题】:Matplotlib Stacked Histogram Bin WidthMatplotlib 堆叠直方图 bin 宽度
【发布时间】:2016-12-30 09:14:50
【问题描述】:

在 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)

我得到以下输出:

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

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果ax.hist-call 的第一个参数是列表列表(或 2d numpy-array 或两者的组合),它将自动使 bin 更小。 ax.hist-call 的rwidth 参数是决定bin-width 的参数。将它设置为 1 会做你想做的事:

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

    【讨论】:

    • 感谢您的回复。你知道为什么默认行为是缩小垃圾箱吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 2016-02-07
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多