【问题标题】:Show two correlation coefficients on pairgrid plot with hue (categorical variable) - seaborn python在带有色调(分类变量)的pairgrid图上显示两个相关系数 - seaborn python
【发布时间】:2017-04-06 09:25:45
【问题描述】:

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

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

非常感谢任何帮助!

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

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

    结果:

    【讨论】:

    • 两种解决方案都运行良好!我选择了第一种解决方案,因为它更自动且更优雅!我现在正在尝试调整函数以适应配对图中的相关系数 - 但没有成功......g = sns.pairplot(df, x_vars=["Probability", "Vagueness"], y_vars=["Climate change attitude"], hue="Sea ice change", kind="reg", markers=["v", "^"] g.map_lower(corrfunc2))我猜这是因为变量分为 X 和 Y 变量?
    • 在不知道到底出了什么问题的情况下很难提供帮助。但是我认为当只有两个子图时,可能会有些混淆,哪些子图应该受到map_lower 的影响。我建议尝试其他映射。
    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多