Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using matplotlib, how could one compare histograms by overlaying them and by showing their ratio plot?

Two histograms can be compared by creating a plot that features both an overlay of the histograms (possibly normalised) and a ratio plot of the histograms. Here is such a plot:

How could a plot like this be made using matplotlib?

like image 860
d3pd Avatar asked Oct 16 '25 04:10

d3pd


1 Answers

I don't see what the dots are, but here's a simple example of the ratios. The main trick is to reuse the bin values that hist returns.

enter image description here

import matplotlib.pyplot as plt
from numpy.random import normal

y = []
y.append(normal(2, 2, size=120))
y.append(normal(2, 2, size=120))

fig, (ax1, ax2) = plt.subplots(nrows=2)

ns, bins, patches = ax1.hist(y, normed=False,
                      histtype='stepfilled',
                      bins=8,
                      alpha=0.2,
                      label=['a','b']
                      )
ax1.legend()

ax2.bar(bins[:-1],     # this is what makes it comparable
        ns[0] / ns[1], # maybe check for div-by-zero!
        alpha=0.4)

ax1.set_ylabel('Data')
ax2.set_ylabel('Ratio (a/b)')
like image 141
cphlewis Avatar answered Oct 17 '25 17:10

cphlewis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!