Python matplotlib直方图上的第一个和最后一个栏显示为已移动

Python matplotlib直方图上的第一个和最后一个栏显示为已移动,python,matplotlib,histogram,Python,Matplotlib,Histogram,我正在尝试使用以下值创建直方图: [1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2, 1, 1, 4, 1, 1, 2, 1, 1, 2] 我使用的代码是 plt.hist(values, histtype='bar', color='green', alpha=0.5) plt.title(library_name, fontsize=12) plt.xlabel(xlabel) plt.ylabel(ylabel) x1, x2, y1, y2 =

我正在尝试使用以下值创建直方图:

[1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2, 1, 1, 4, 1, 1, 2, 1, 1, 2]
我使用的代码是

plt.hist(values, histtype='bar', color='green', alpha=0.5)
plt.title(library_name, fontsize=12)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.savefig("../results/histograms/" + library_name)
我得到了这个直方图

有人知道为什么第一个和最后一个酒吧的外观与他们的xtick不同吗?我尝试使用plt.margins函数,但没有结果


非常感谢

要使垃圾箱居中对齐而不是左对齐,请使用
plt.hist(数据,垃圾箱=np.arange(50)-0.5)

示例代码:

import matplotlib.pyplot as plt
import numpy as np

values = [1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2,5,3,2,5, 1, 1, 4, 1, 1, 2, 1, 1,7,8,9,9,3,8,6, 2]

offset = 0.5

plt.hist(values,  bins=np.arange(1,np.max(values)+2)-offset, histtype='bar', color='green', alpha=0.5)
plt.title('library_name', fontsize=12)
plt.xlabel('xlabel')
plt.ylabel('ylabel')
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.show()

顺便说一句,您可以使用[免责声明:我写的[/strong>]physt”库,它有两个装箱选项,包括一个适合整数的装箱选项-请参阅,特别是针对您的案例

代码如下所示:

import physt
h = physt.histogram(values, "integer")
ax = h.plot(color="green", alpha=0.5, ticks="center")

…然后添加轴/plt格式…

谢谢@Samuel Bancroft。有没有一种方法可以在不指定直方图中条的恒定最大值的情况下实现这一点(在本例7中)?我希望它尽可能通用,没问题。我已经更新了代码,使它更通用。希望有帮助!matplotlib binning是非常自动的,并且对您想要的内容漠不关心。默认情况下,它会在最小值和最大值之间创建10个箱子。因此,在许多情况下,您必须手动指定垃圾箱(如Samuel Bancroft的回答)谢谢,看起来很棒