gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:24:33 26 4
gpt4 key购买 nike

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

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

非常感谢任何帮助!

最佳答案

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

关于python - 在带有色调(分类变量)的pairgrid图上显示两个相关系数 - seaborn python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com