关于matplotlib直方图不居中的解决方案

import matplotlib.pyplot as plt
import numpy as np
test = [12, 37, 87, 70, 70, 19, 45, 59, 91, 21, 25, 27, 76, 46, 46, 51, 22, 80, 30, 23,\
 48, 68, 31, 60, 41, 44, 77, 65, 23, 57, 38, 76, 18, 22, 47, 35, 91, 51, 65, 56,\
 69, 45, 75, 23, 67, 28, 58, 21, 53, 21, 78, 75, 68, 75, 29, 30, 32, 58, 95, 80] 
label=np.arange(0,101,10)
plt.subplot(2,1,1)
plt.hist(test,rwidth=0.8,bins=10)
plt.title('3a: Mark distribution')
plt.subplot(2,1,2)
plt.hist(test,bins=10,rwidth=0.8)
plt.xticks(label)
plt.title('3b: Mark distribution')

plt.subplots_adjust(hspace=0.6)
plt.show()

如上图,直方图不跟着刻度居中,烦

原因好像是他分的区间没有设定,bins=10改成list就ok了
改正后的代码

import matplotlib.pyplot as plt
import numpy as np
test = [12, 37, 87, 70, 70, 19, 45, 59, 91, 21, 25, 27, 76, 46, 46, 51, 22, 80, 30, 23,\
 48, 68, 31, 60, 41, 44, 77, 65, 23, 57, 38, 76, 18, 22, 47, 35, 91, 51, 65, 56,\
 69, 45, 75, 23, 67, 28, 58, 21, 53, 21, 78, 75, 68, 75, 29, 30, 32, 58, 95, 80] 
label=np.arange(0,101,10)
plt.subplot(2,1,1)
plt.hist(test,rwidth=0.8,bins=10)
plt.title('3a: Mark distribution')
plt.subplot(2,1,2)
plt.hist(test,bins=range(0,100,10),rwidth=0.8)
plt.xticks(label)
plt.title('3b: Mark distribution')

plt.subplots_adjust(hspace=0.6)
plt.show()

posted @ 2021-06-09 01:24  Duan2baka  阅读(451)  评论(0编辑  收藏  举报