Seaborn:带有边缘直方图的 kdeplot

mal*_*ave 4 python matplotlib seaborn

我使用kdeplot来绘制两个二元分布的密度,如下所示,其中df_cdf_n是两个 Pandas DataFrame:

f, ax = plt.subplots(figsize=(6, 6))
sns.kdeplot(df_c['attr1'], df_c['attr2'], ax=ax, cmap='Blues', shade_lowest=False)
sns.kdeplot(df_n['attr1'], df_n['attr2'], ax=ax, cmap='Reds',  shade_lowest=False)
Run Code Online (Sandbox Code Playgroud)

我还想包括边际直方图,例如由jointplot生成的边际直方图(示例图)。但是,我无法使用 jointplot (因为显然不可能用 jointplot 绘制两个不同的分布,因为每次调用它时它都会生成一个新的图形),并且我找不到有关如何重现它生成的边际直方图的任何信息。

有没有一种简单的方法可以使用 Seaborn / matplotlib 生成带有边缘直方图的 kdeplot?或者,我是否忽略了使用联合图绘制两个单独分布的方法?

Y. *_*Luo 5

您可以使用seaborn.JointGrid正如seaborn的作者在这个Github问题中所解释的那样,关键是使用

“属性上的三个分量轴称为ax_jointax_marg_xax_marg_y”。

希望以下示例是您想要的:

import matplotlib.pyplot as plt
import seaborn as sns

iris = sns.load_dataset("iris")
setosa = iris.loc[iris.species == "setosa"]
virginica = iris.loc[iris.species == "virginica"]

g = sns.JointGrid(x="sepal_width", y="petal_length", data=iris)
sns.kdeplot(setosa.sepal_width, setosa.sepal_length, cmap="Reds",
            shade=True, shade_lowest=False, ax=g.ax_joint)
sns.kdeplot(virginica.sepal_width, virginica.sepal_length, cmap="Blues",
            shade=True, shade_lowest=False, ax=g.ax_joint)
sns.distplot(setosa.sepal_width, kde=False, color="r", ax=g.ax_marg_x)
sns.distplot(virginica.sepal_width, kde=False, color="b", ax=g.ax_marg_x)
sns.distplot(setosa.sepal_length, kde=False, color="r", ax=g.ax_marg_y, vertical=True)
sns.distplot(virginica.sepal_length, kde=False, color="b", ax=g.ax_marg_y, vertical=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述