Skip to content Skip to sidebar Skip to footer

How To Plot Multiple Histograms On Same Plot With Seaborn

With matplotlib, I can make a histogram with two datasets on one plot (one next to the other, not overlay). import matplotlib.pyplot as plt import random x = [random.randrange(100

Solution 1:

If I understand you correctly you may want to try something this:

fig, ax = plt.subplots()
for a in [x, y]:
    sns.distplot(a, bins=range(1, 110, 10), ax=ax, kde=False)
ax.set_xlim([0, 100])

Which should yield a plot like this:

enter image description here

UPDATE:

Looks like you want 'seaborn look' rather than seaborn plotting functionality. For this you only need to:

import seaborn as sns
plt.hist([x, y], color=['r','b'], alpha=0.5)

Which will produce:

enter image description here


Solution 2:

Merge x and y to DataFrame, then use histplot with multiple='dodge' and hue option:

import random

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

x = [random.randrange(100) for _ in range(100)]
y = [random.randrange(100) for _ in range(100)]
df = pd.concat(axis=0, ignore_index=True, objs=[
    pd.DataFrame.from_dict({'value': x, 'name': 'x'}),
    pd.DataFrame.from_dict({'value': y, 'name': 'y'})
])
fig, ax = plt.subplots()
sns.histplot(
    data=df, x='value', hue='name', multiple='dodge',
    bins=range(1, 110, 10), ax=ax
)
ax.set_xlim([0, 100])

Resulting Plot


Post a Comment for "How To Plot Multiple Histograms On Same Plot With Seaborn"