How to draw 2 histograms in 1 table?

Viewed 50

I was planning to combine these 2 histograms under 1 table. Also, they need to be side by side, i.e., data cannot overlap each other.

import matplotlib.pyplot as plt    

df.hist(column='oq_len', bins = 25, color = 'blue')
df.hist(column='cq_len', bins = 25, color = 'red')
    
plt.show()

enter image description here

enter image description here

1 Answers

Using seaborn, histograms can be combined. multiple='dodge' will place the bars for different columns next to each other. shrink=0.8 will make the bars a bit narrower (default they occupy all available space).

The original plot gives the impression that the values are all integers. The bin edges should take this into account. sns.histplot's dicrete=True parameter takes care of that.

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns
import pandas as pd
import numpy as np

df = pd.DataFrame({'cq_len': np.random.geometric(p=0.25, size=500).clip(0, 15),
                   'oq_len': np.random.geometric(p=0.31, size=500).clip(0, 15)})
sns.set_style('whitegrid')
plt.figure(figsize=(12, 5))
ax = sns.histplot(data=df, discrete=True, multiple='dodge', shrink=0.8)
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.margins(x=0.01)
plt.show()

sns.histplot with multiple='dodge'

Related