您好,我想绘制一个直方图,箱线图出现在直方图的顶部,显示 Q1、Q2 和 Q3 以及异常值。示例电话如下。 (我正在使用 Python 和 Pandas)
我已经检查了几个使用 matplotlib.pyplot
的例子,但很难找到一个好的例子。我还想让直方图曲线如下图所示。
我还尝试了 seaborn
,它为我提供了形状线和直方图,但没有找到与上面的 boxpot 合并的方法。
任何人都可以帮助我在 matplotlib.pyplot
上或使用 pyplot
最佳答案
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)
来自 seaborn v0.11.2
,sns.distplot
已弃用。使用 sns.histplot
取而代之的是轴级图。
np.random.seed(2022)
x = np.random.randn(100)
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)})
sns.boxplot(x=x, ax=ax_box)
sns.histplot(x=x, bins=12, kde=True, stat='density', ax=ax_hist)
ax_box.set(yticks=[])
sns.despine(ax=ax_hist)
sns.despine(ax=ax_box, left=True)
关于python - 在 Python 中使用上面的箱线图绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381330/