PairGrid 上的 Seaborn 相关系数 [英] Seaborn Correlation Coefficient on PairGrid

查看:55
本文介绍了PairGrid 上的 Seaborn 相关系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有我可以与 g.map_lower 或 g.map_upper 一起使用的 matplotlib 或 seaborn 图来为每个双变量图显示相关系数,如下所示?手动映射 plt.text 以获得以下示例,这是一个繁琐的过程.

Is there a matplotlib or seaborn plot I could use with g.map_lower or g.map_upper to get the correlation coefficient displayed for each bivariate plot like shown below? plt.text was manually mapped to get the below example which is a tedious process.

推荐答案

您可以将任何函数传递给 map_* 方法,只要它遵循一些规则:1) 它应该绘制到当前"轴,2)它应该接受两个向量作为位置参数,3)它应该接受一个 color 关键字参数(如果你想与 hue 兼容,可以选择使用它 选项).

You can pass any function to the map_* methods as long as it follows a few rules: 1) it should plot onto the "current" axes, 2) it should take two vectors as positional arguments, and 3) it should accept a color keyword argument (optionally using it, if you want to be compatible with the hue option).

因此,在您的情况下,您只需要定义一个小 corrfunc 函数,然后将其映射到您想要注释的轴上:

So in your case you just need to define a little corrfunc function and then map it across the axes you want to have annotated:

import numpy as np
from scipy import stats
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")

mean = np.zeros(3)
cov = np.random.uniform(.2, .4, (3, 3))
cov += cov.T
cov[np.diag_indices(3)] = 1
data = np.random.multivariate_normal(mean, cov, 100)
df = pd.DataFrame(data, columns=["X", "Y", "Z"])

def corrfunc(x, y, **kws):
    r, _ = stats.pearsonr(x, y)
    ax = plt.gca()
    ax.annotate("r = {:.2f}".format(r),
                xy=(.1, .9), xycoords=ax.transAxes)

g = sns.PairGrid(df, palette=["red"])
g.map_upper(plt.scatter, s=10)
g.map_diag(sns.distplot, kde=False)
g.map_lower(sns.kdeplot, cmap="Blues_d")
g.map_lower(corrfunc)

这篇关于PairGrid 上的 Seaborn 相关系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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