modLmakur
modLmakur

Reputation: 573

Overlay histograms in one plot

I have two dataframes that I'm trying to make histograms of. I would like to overlay one histogram over the other and show them in the same cell, so I can easily compare the distributions. Can anyone suggest how to do that? I have example code and data below. This will plot the histograms separately one above the other.

Data:

print(df[1:5])

 bob
1 1
2 3
3 5
4 1  

print(df2[1:5])

 bob
1 3
2 3
3 2
4 1         

Code:

    import pandas as pd
    import matplotlib.pyplot as plt
    %matplotlib inline

    df[df[bob]>=1][bob].hist(bins=25, range=[0, 25])
    plt.show()
    df2[df2[bob]>=1][bob].hist(bins=25, range=[0, 25])
    plt.show()

Upvotes: 1

Views: 2791

Answers (1)

Lambda
Lambda

Reputation: 1392

Use ax:

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure() 
ax = fig.add_subplot(111)

df = pd.DataFrame([1, 3, 5, 1], columns=["bob"], index=[1, 2, 3, 4])
df2 = pd.DataFrame([3, 3, 2, 1], columns=["bob"], index=[1, 2, 3, 4])

ax.hist([df, df2], label=("df", "df2"), bins=25, range=[0, 25])
ax.legend()

Upvotes: 2

Related Questions