简体   繁体   中英

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.

How would I do that in 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? 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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