python - matplotlib 直方图上的第一个和最后一个条出现移动

标签 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 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.savefig("../results/histograms/" + library_name)

然后我得到了这个直方图 histogram with first and last bars poorly located

有谁知道为什么第一个和最后一个柱看起来与它们的 xtick 不同?我尝试使用 plt.margins 函数但没有结果。

非常感谢

最佳答案

要获得中心对齐的 bin 而不是左对齐,请使用 plt.hist(data, bins=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()

关于python - matplotlib 直方图上的第一个和最后一个条出现移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38721086/

相关文章:

python - 绘制给定均值和西格玛的正态分布 - python

python - 多个子图的 GridSpec "the figure containing the passed axes is being cleared"

python-3.x - 如何使用控制小部件将子图添加到绘图中

c++ - 从值数组创建直方图/绘图

arrays - Matlab:创建合并的 RGB 直方图

python - 创建 Python Web 服务器 - 布局和设置

python - 如何将数据框/列表写入 csv 文件?

python - blender - 导入 pandas ImportError : No module named pandas

python - Scrapy 从任何网站获取所有链接

python - 使用 matplotlib 在一个图中绘制多个直方图