在Python中使用Boxplot的直方图

Isu*_*mal 8 python matplotlib histogram boxplot seaborn

嗨,我想绘制一个直方图,其中显示直方图顶部的箱线图,显示Q1,Q2和Q3以及异常值.示例电话如下.(我使用的是Python和Pandas) 在此输入图像描述

我已经检查了几个使用的例子,matplotlib.pyplot但几乎没有一个很好的例子.我还希望直方图曲线如下图所示. 在此输入图像描述

我也试过seaborn,它提供了形状线和直方图,但没有找到一种方法与它上面的boxpot结合.

任何人都可以帮我这个有这个matplotlib.pyplot或使用pyplot

mwa*_*kom 14

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="ticks")

x = np.random.randn(100)

f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, 
                                    gridspec_kw={"height_ratios": (.15, .85)})

sns.boxplot(x, ax=ax_box)
sns.distplot(x, ax=ax_hist)

ax_box.set(yticks=[])
sns.despine(ax=ax_hist)
sns.despine(ax=ax_box, left=True)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


eri*_*fis 5

仅使用 matplotlib 的解决方案,只是因为:

# start the plot: 2 rows, because we want the boxplot on the first row
# and the hist on the second
fig, ax = plt.subplots(
    2, figsize=(7, 5), sharex=True,
    gridspec_kw={"height_ratios": (.3, .7)}  # the boxplot gets 30% of the vertical space
)

# the boxplot
ax[0].boxplot(data, vert=False)

# removing borders
ax[0].spines['top'].set_visible(False)
ax[0].spines['right'].set_visible(False)
ax[0].spines['left'].set_visible(False)

# the histogram
ax[1].hist(data)

# and we are good to go
plt.show()
Run Code Online (Sandbox Code Playgroud)