向 seaborn 散点图添加相关系数

问题描述 投票:0回答:3

我目前正在使用

sns.scatterplot
功能绘制 2 个变量之间的一些数值关系,并想将标签添加到显示 2 个变量之间的相关系数的散点图作为我的图上的注释。

我如何在 python/seaborn 中做到这一点?

我试着在这里查看 sns 页面 https://seaborn.pydata.org/generated/seaborn.scatterplot.html 对于这个例子:

sns.scatterplot(data=tips, x="total_bill", y="tip")
但找不到任何帮助?这里有运气吗?谢谢!

python seaborn visualization correlation scatter-plot
3个回答
3
投票

这可能有帮助:

# 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()

0
投票

基于 Leon Shpaner 回答的可运行示例:

import scipy as sp
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
sns.set_theme(style="ticks")

x_data = [1,2,3,4,5,6,7,8,9]
y_data = [1,3,2,4,5,6,7,9,8]
sns.scatterplot(x=x_data, y=y_data)

plt.title('Title')
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')

r, p = sp.stats.pearsonr(x=x_data, y=y_data)
ax = plt.gca() # Get a matplotlib's axes instance
plt.text(.05, .8, "Pearson's r ={:.2f}".format(r), transform=ax.transAxes)
plt.savefig('Scatterplot with Pearson r.png', bbox_inches='tight', dpi=300)
plt.close()

输出:


0
投票

基于 Leon Shpaner 回答的可运行示例:

import scipy as sp
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
sns.set_theme(style="ticks")

x_data = [1,2,3,4,5,6,7,8,9]
y_data = [1,3,2,4,5,6,7,9,8]
sns.scatterplot(x=x_data, y=y_data)

plt.title('Title')
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')

r, p = sp.stats.pearsonr(x=x_data, y=y_data)
ax = plt.gca() # Get a matplotlib's axes instance
plt.text(.05, .8, "Pearson's r ={:.2f}".format(r), transform=ax.transAxes)
plt.savefig('Scatterplot with Pearson r.png', bbox_inches='tight', dpi=300)
plt.close()

输出:

相关,仍在 Python 中,但没有

seaborn
How to overplot on a scatter plot in python?

© www.soinside.com 2019 - 2024. All rights reserved.