简体   繁体   English

将相关系数添加到 seaborn 散点图 plot

[英]Adding correlation coefficient to a seaborn scatter plot

I am currently plotting some numerical relationships between 2 variables with the sns.scatterplot functionality, and would like to add the label to the scatterplot that shows the correlation coefficient between the 2 variables as an annotation on my plots.我目前正在使用sns.scatterplot功能绘制 2 个变量之间的一些数值关系,并希望将 label 添加到散点图中,该散点图中显示 2 个变量之间的相关系数作为我的图上的注释。

How would I do that in python/seaborn?我将如何在 python/seaborn 中做到这一点?

I tried looking at the sns page here https://seaborn.pydata.org/generated/seaborn.scatterplot.html for this example: sns.scatterplot(data=tips, x="total_bill", y="tip") but was unable to find any help?我尝试在此处查看 sns 页面https://seaborn.pydata.org/generated/seaborn.scatterplot.html对于此示例: sns.scatterplot(data=tips, x="total_bill", y="tip")但是找不到任何帮助? any luck here?这里有运气吗? thanks !谢谢 !

Hopefully, this helps.希望这会有所帮助。

# import the scipy library
import scipy as sp
# call the seaborn scatterplot function per usual
sns.scatterplot(data=df, x=df['col1'] y=df['col2'], hue='col3')

# define titles and axes labels
plt.title('Title')
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')

# call the scipy function for pearson correlation
r, p = sp.stats.pearsonr(x=df['col1'] y=df['col2'])
# annotate the pearson correlation coefficient text to 2 decimal places
plt.text(.05, .8, 'r={:.2f}'.format(r), transform=ax.transAxes)

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM