【问题标题】:Seaborn JointGrid/plot_joint: multiple scatter plots unable to annotate RsquareSeaborn JointGrid/plot_joint:多个散点图无法注释 Rsquare
【发布时间】:2017-01-24 19:03:56
【问题描述】:

我在使用 seaborn JointGrid 和 plot_joint 函数时遇到了问题。我有多个散点图,我正在执行线性回归,并且我有一个图例,但是当我尝试用每条线的 rqsuare 值注释该图时,它似乎不起作用。相反,它会更改第一个散点图的颜色。

这是我的代码的缩短版本(我正在绘制 x 和 z,并使用 x_sections 将数据分成 4 个我想要 Rsquare 的分布):

import seaborn as sns
import numpy as np
import itertools
import matplotlib.pyplot as plt

palette = itertools.cycle(sns.color_palette())
legend_labels = ['a','b','c','d']
x_sections = np.array([[1,3],[5,6],[10,11],[18,19]])
x = np.arange(1,20,0.1) #e.g. of data
z = np.random.rand(np.size(x))*x #e.g. of data

min_x= np.searchsorted(x,x_sections[0][0])
max_x= np.searchsorted(x,x_sections[0][1])
g = sns.JointGrid(x[min_x:max_x],z[min_x:max_x],xlim=(0,20),ylim=(0,20))
g.plot_joint(plt.scatter,color=next(palette),label=legend_labels[0])
rsquare = lambda a, b: stats.pearsonr(a, b)[0] ** 2
#g.annotate(rsquare, template="{stat}: {val:.2f}",stat="$R^2$", loc="upper left")
g.plot(sns.regplot,sns.distplot)

for i in range(1,len(x_sections)):
    min_x= np.searchsorted(x,x_sections[i][0])
    max_x= np.searchsorted(x,x_sections[i][1])
    g.x = x[min_x:max_x]
    g.y = z[min_x:max_x]
    g.plot_joint(plt.scatter,color=next(palette),label=legend_labels[i])
    g.plot(sns.regplot,sns.distplot)
    #g.annotate(rsquare, template="{stat}: {val:.2f}",stat="$R^2$", loc="upper left")

 plt.legend()

此代码生成四个分布的图(非常丑陋,但仅用于示例目的)。当我取消注释 g.annotate 代码行时,我希望 R^2 值会在图上进行注释,但它会改变散点图分布的颜色。我不确定发生了什么,任何帮助将不胜感激!

干杯。

【问题讨论】:

  • 注解使用ax.legend(利用loc="best")行为,其中只能有一个。由于您已经在编写一些额外的代码,我建议您使用 ax.text 添加自己的注释。
  • 感谢您的评论。我不确定如何实现这一点。我不能使用g.textplt.text 不会在情节上产生任何文字。如果您不介意向我展示如何实现它,我发布的代码可以粘贴到 python 中。谢谢。
  • @mwaskom 抱歉忘记在我之前的评论中标记你,你介意告诉我你将如何在示例中实现 ax.text 吗?干杯

标签: plot seaborn annotate


【解决方案1】:

这是一个老问题,但解决问题的关键是访问坐标轴,它们是JointGrid 的成员。

替换旧注释:

g.annotate(rsquare, template="{stat}: {val:.2f}",stat="$R^2$", loc="upper left")

与新的:

g.ax_joint.text(xy=(1.0, 13.0), s="R^2: {:.2f}".format(
    rsquare(x[min_x:max_x],z[min_x:max_x])
))

但这要求您可以为文本指定适当的 (x, y) 坐标。使用 g.ax_joint.annotation(...) 也需要 xy 坐标。更优雅的方法可能是在循环中将 r^2 值附加到轴标签。

...
    r_2 = rsquare(x[min_x:max_x], z[min_x:max_x])
    g.plot_joint(plt.scatter, color=next(palette),
        label=legend_labels[i] + " : R^2 = {:.2f}".format(r_2))
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 2021-02-20
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2020-10-18
    相关资源
    最近更新 更多