在带有色调(分类变量)的pairgrid图上显示两个相关系数 - seaborn python

Mar*_*ieJ 6 python seaborn

我找到了一个函数来计算相关系数,然后将其添加到配对图中(如下所示)。我的问题是,当我运行带有色调(分类变量)的配对图时,两组的相关系数显示在彼此之上。

这就是情节的样子

这是我的图形代码(它显示了气候变化态度和峰值之间的相关系数作为“海冰方向”的函数):

`g = sns.PairGrid(df, vars = ['OverallClimateChangeAttitude', 'Peak'], 
hue="IV_SeaIceChangeDirection")
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)`
Run Code Online (Sandbox Code Playgroud)

这是相关函数:

`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)`
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助!

ger*_*eth 8

问题是您的相关函数指定了应放置注释的确切位置,并且该位置(.1, .9)对于两种色调都是相同的。您需要以某种方式为不同类别的数据选择不同的位置。我想了两种方法来做到这一点:

  • 要么计算轴中已有多少注释,以将新注释放置在其余注释下方
  • hue或者手动为每个值预定义位置并使用kws['label']来选择要采用的值。

请参阅corrfunc下面的代码了解这两个选项。我用其余的代码和示例数据集绘制了一个图。我还在注释中添加了标签文本,否则我无法区分哪个相关系数是哪个。

from scipy import stats
import seaborn as sns
import matplotlib

def corrfunc(x, y, **kws):
    r, _ = stats.pearsonr(x, y)
    ax = plt.gca()
    # count how many annotations are already present
    n = len([c for c in ax.get_children() if 
                  isinstance(c, matplotlib.text.Annotation)])
    pos = (.1, .9 - .1*n)
    # or make positions for every label by hand
    pos = (.1, .9) if kws['label'] == 'Yes' else (.1,.8)

    ax.annotate("{}: r = {:.2f}".format(kws['label'],r),
                xy=pos, xycoords=ax.transAxes)

tips = sns.load_dataset("tips")
g = sns.PairGrid(data = tips, vars = ['tip', 'total_bill'], hue="smoker", size=4)
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)
g.add_legend()
Run Code Online (Sandbox Code Playgroud)

结果:

带注释的 Seaborn 对图