【问题标题】:Python: Align bars between bin edges for a double histogramPython:为双直方图对齐 bin 边缘之间的条形图
【发布时间】:2018-01-12 08:37:27
【问题描述】:

我无法使用 pyplot.hist 函数在同一个图上绘制 2 个直方图。对于每个分箱间隔,我希望 2 个条在箱之间居中(Python 3.6 用户)。为了说明,这里是一个例子:

import numpy as np
from matplotlib import pyplot as plt

bin_width=1

A=10*np.random.random(100)
B=10*np.random.random(100)

bins=np.arange(0,np.round(max(A.max(),B.max())/bin_width)*bin_width+2*bin_width,bin_width)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.hist(A,bins,color='Orange',alpha=0.8,rwidth=0.4,align='mid',label='A')

ax.hist(B,bins,color='Orange',alpha=0.8,rwidth=0.4,align='mid',label='B')

ax.legend()
ax.set_ylabel('Count')

我明白了:

Histogram_1

A和B系列重叠,不好。知道“对齐”只有 3 个选项(以左侧 bin 为中心,在 2 个 bin 中间,以右侧 bin 为中心),我看到除了修改 bin 之外没有其他选项,添加:

bins-=0.25*bin_width 

在绘制 A 并添加之前:

bins+=0.5*bin_width

在绘制 B 之前。这给了我:Histogram

这样更好!但是,我不得不修改分箱,所以 A 和 B 不一样。

我搜索了一种使用相同分箱的简单方法,然后移动第一个和第二个图,以便它们正确显示在分箱间隔中,但我没有找到。有什么建议吗?

我希望我清楚地解释了我的问题。

【问题讨论】:

  • 你不能指望像plt.hist 这样的便利包装器能够解释可能存在的每一个异常情况。由于您有一个两步过程,因此请将其分开。使用np.histogram 使用您喜欢的任何设置计算您的直方图。然后使用 plt.bar 使用您喜欢的任何设置绘制结果。
  • 好主意,现在可以使用了 :) 谢谢!

标签: python python-3.x numpy matplotlib histogram


【解决方案1】:

正如前面在上面的评论中提到的,您不需要 hist plot 函数。使用 numpy histogram 函数并用 matplotlib 的 bar 函数绘制结果。

根据 bin 数量和数据类型的计数,您可以计算 bin 宽度。您可以使用 xticks 方法调整刻度:

import numpy as np
import matplotlib.pylab as plt

A=10*np.random.random(100)
B=10*np.random.random(100)

bins=20
# calculate heights and bins for both lists
ahist, abins = np.histogram(A, bins)
bhist, bbins = np.histogram(B, abins)

fig = plt.figure()
ax = fig.add_subplot(111)
# calc bin width for two lists
w = (bbins[1] - bbins[0])/3.
# plot bars
ax.bar(abins[:-1]-w/2.,ahist,width=w,color='r')
ax.bar(bbins[:-1]+w/2.,bhist,width=w,color='orange')
# adjsut xticks
plt.xticks(abins[:-1], np.arange(bins))

plt.show()

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多