Skip to main content
 首页 » 编程设计

python之Matplotlib:如何绘制两个直方图的差异

2025年05月04日14jackei

假设您有以下数据集:

a=[1, 2, 8, 9, 5, 6, 8, 5, 8, 7, 9, 3, 4, 8, 9, 5, 6, 8, 5, 8, 7, 9, 10] 
b=[1, 8, 4, 1, 2, 4, 2, 3, 1, 4, 2, 5, 9, 8, 6, 4, 7, 6, 1, 2, 2, 3, 10] 

并假设您生成了他们的直方图:

import matplotlib.pyplot as plt 
 
fig, ax = plt.subplots(1,2,figsize=(16, 8)) 
 
plt.subplot(121) 
plot1=plt.hist(a, bins=[0,1,2,3,4,5,6,7,8,9,10], 
normed=True,edgecolor='k',linewidth=1.0,color='blue') 
plt.title("a") 
 
plt.subplot(122) 
plot2=plt.hist(b, bins=[0,1,2,3,4,5,6,7,8,9,10], 
normed=True,edgecolor='k',linewidth=1.0,color='green') 
plt.title("b") 
 
plt.show() 

如何生成具有相同 bin 和高度的两个直方图之间差异的条形图?

如果你这样做:

 diff=plt.bar([1,2,3,4,5,6,7,8,9,10],  
             height=(plot1[0]-plot2[0]), edgecolor='black',  
             linewidth=1.2, color='red',width = 1)  
 plt.title("a-b") 

x 轴上的值未与 bin 对齐。如何解决这个问题?

请您参考如下方法:

好吧,如果我正确理解了你的问题,那么解决方案就非常简单——如果你像前两个直方图一样将差异的 bins 设置为从 0 开始,并将对齐设置为边缘,那么它看起来效果很好。

diff=plt.bar([0,1,2,3,4,5,6,7,8,9],  
             height=(plot1[0]-plot2[0]), edgecolor='black',  
             linewidth=1.2, color='red',width = 1, align = 'edge')  
plt.title("a-b") 
plt.show()