Skip to main content
 首页 » 编程设计

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

2025年04月02日1452php

我正在尝试使用这些值创建直方图:

[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 函数但没有结果。

非常感谢

请您参考如下方法:

要获得中心对齐的 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()