Hi I wanted to draw a histogram with a boxplot appearing the top of the histogram showing the Q1,Q2 and Q3 as well as the outliers. Example phone is below. (I am using Python and Pandas)
I have checked several examples using matplotlib.pyplot
but hardly came out with a good example. And I also wanted to have the histogram curve appearing like in the image below.
I also tried seaborn
and it provided me the shape line along with the histogram but didnt find a way to incorporate with boxpot above it.
can anyone help me with this to have this on matplotlib.pyplot
or using pyplot
Advertisement
Answer
JavaScript
x
18
18
1
import numpy as np
2
import seaborn as sns
3
import matplotlib.pyplot as plt
4
5
sns.set(style="ticks")
6
7
x = np.random.randn(100)
8
9
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True,
10
gridspec_kw={"height_ratios": (.15, .85)})
11
12
sns.boxplot(x, ax=ax_box)
13
sns.distplot(x, ax=ax_hist)
14
15
ax_box.set(yticks=[])
16
sns.despine(ax=ax_hist)
17
sns.despine(ax=ax_box, left=True)
18
From seaborn v0.11.2
, sns.distplot
is deprecated. Use sns.histplot
for axes-level plots instead.
JavaScript
1
12
12
1
np.random.seed(2022)
2
x = np.random.randn(100)
3
4
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)})
5
6
sns.boxplot(x=x, ax=ax_box)
7
sns.histplot(x=x, bins=12, kde=True, stat='density', ax=ax_hist)
8
9
ax_box.set(yticks=[])
10
sns.despine(ax=ax_hist)
11
sns.despine(ax=ax_box, left=True)
12