2017-04-06 43 views
1

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

this is how the plot looks like

这是我的图形码(其示出了气候变化态度和峰值为“海冰方向”的功能之间的相关系数在彼此的顶部):

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

这里是相关函数:

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

任何帮助非常感谢!

回答

0

问题是,您的相关函数指定了应该放置注释的确切位置,并且该位置是(.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() 

结果:

seaborn pairplot with annotations

+0

这是优秀的,谢谢!@Gereleth – MarieJ

+0

这两个解决方案工作得非常好!我选择了第一种解决方案,因为它更自动,更优雅!我现在试图调整函数来拟合一对图中的相关系数 - 但是没有成功...... g = sns.pairplot(df,x_vars = [“概率”,“模糊度”],y_vars = [“气候改变态度“], hue =”海冰变化“,kind =”reg“,markers = [”v“,”^“] g.map_lower(corrfunc2))'我猜这是因为变量被分成X和Y变量? – MarieJ

+0

不知道究竟发生了什么错误,很难提供帮助。但是我认为当只有两个子图受到'map_lower'的影响时,可能会出现一些混淆。我会建议尝试其他映射。 – gereleth

相关问题