Seaborn: kdeplots with marginal histograms

荒凉一梦 提交于 2020-01-02 08:45:50

问题


I'm using a kdeplot to plot the densities of two bivariate distributions like this, where df_c and df_n are two Pandas DataFrames:

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)

I would like to also include marginal histograms like those generated by jointplot (example plot). However, I cannot use jointplot (because it is appearantly not possible to plot two different distributions with jointplot, as it will generate a new Figure every time it is called), and I cannot find any information on how to reproduce the marginal histograms it produces.

Is there an easy way to produce a kdeplot with marginal histograms using Seaborn / matplotlib? Alternatively, did I overlook a way to plot two separate distributions using a jointplot?


回答1:


You can use seaborn.JointGrid. The key, as explained by seaborn's author in this Github issue, is to use

"three component axes at attributes called ax_joint, ax_marg_x, and ax_marg_y".

Hopefully the following example is what you want:

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()



来源:https://stackoverflow.com/questions/49654812/seaborn-kdeplots-with-marginal-histograms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!