Reputation: 7909
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?
Upvotes: 2
Views: 7860
Reputation: 84
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()
Upvotes: 7