Seaborn:具有边际直方图的kdeplots [英] Seaborn: kdeplots with marginal histograms

查看:44
本文介绍了Seaborn:具有边际直方图的kdeplots的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

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?

解决方案

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

这篇关于Seaborn:具有边际直方图的kdeplots的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆