【问题标题】:Seaborn: kdeplots with marginal histogramsSeaborn:带有边缘直方图的 kdeplots
【发布时间】:2018-09-14 05:45:49
【问题描述】:

我正在使用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)

我还想包括由jointplot (example plot) 生成的边缘直方图。但是,我不能使用jointplot(因为似乎不可能用jointplot绘制两个不同的分布,因为每次调用它都会生成一个新的图形),而且我找不到任何关于如何重现它产生的边际直方图的信息.

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

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    您可以使用seaborn.JointGrid。正如 seaborn 的作者在this Github issue 中所解释的那样,关键是使用

    “三个分量轴在属性称为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()
    

    【讨论】:

    • 谢谢,就像一个魅力。 (我认为您忘记添加指向您所指的 GitHub-Issue 的链接)
    • @malexmave 对不起。我刚刚添加了链接。感谢您指出这一点。
    猜你喜欢
    • 2019-10-23
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2015-11-24
    相关资源
    最近更新 更多