Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why do 2 histograms overlap in matplotlib?

In this python script is an attempt to create two histogram in one figure but the second histogram overlaps the first one

from random import randrange
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(50,50))
ids = [ str(randrange(10000, 99999)) for i in range(1000)]
ids2 = [ str(randrange(10000, 99999)) for i in range(1000)]
def fun1():
    ax = fig.add_subplot(1, 1, 1)
    n, bins, patches = ax.hist(x=ids, bins=range(500))
    ax.grid(axis='y', alpha=0.6)
    fig.tight_layout(pad=3.0, w_pad=2.0, h_pad=2.0)

def fun2():
    ax2 = fig.add_subplot(2, 1, 2)
    n, bins, patches = ax2.hist(x=ids2, bins=range(500))
    ax2.grid(axis='y', alpha=0.6)
  
fun1()
fun2()

although I used tight_layout this does not help with the overlapping of the two histograms.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have specified the subplots in this order

ax = fig.add_subplot(1, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

What you meant should be this

ax = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

(2, 1) will arrange the plots in 2 rows and 1 column, then the third parameter is to specify subplots 1 and 2

enter image description here

If you specify (1, 2) there will be 1 row and 2 columns

ax = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading