简体   繁体   中英

Matplotlib: how to plot the difference of two histograms?

Say you have the following datasets:

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]

and say you produce their histograms:

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()

在此处输入图片说明

How do you produce a barplot with the same bins and for heights the difference between the two histograms?

If you do something like this:

 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")

the values on the x axis are not aligned with the bins. How to fix this? 在此处输入图片说明

Okay, if I understood your problem correctly the solution is quite simple - if you set the bins for difference to start from 0 as in the two previous histograms and set align to edge it seems that it works well.

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()

看到我的输出图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM