在 python 中使用 seaborn 在 pairplot 中显示相关值
Show correlation values in pairplot using seaborn in python
我有以下数据:
prop_tenure prop_12m prop_6m
0.00 0.00 0.00
0.00 0.00 0.00
0.06 0.06 0.10
0.38 0.38 0.25
0.61 0.61 0.66
0.01 0.01 0.02
0.10 0.10 0.12
0.04 0.04 0.04
0.22 0.22 0.22
我正在做一个配对图,如下所示:
sns.pairplot(data)
plt.show()
不过,我想显示变量之间的相关系数,如果可能的话,还想显示每个变量的偏度和峰度。
你如何在 seaborn 中做到这一点?
据我所知,没有开箱即用的功能可以执行此操作,您必须 :
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
def corrfunc(x, y, ax=None, **kws):
"""Plot the correlation coefficient in the top left hand corner of a plot."""
r, _ = pearsonr(x, y)
ax = ax or plt.gca()
ax.annotate(f'ρ = {r:.2f}', xy=(.1, .9), xycoords=ax.transAxes)
使用您输入的示例:
import seaborn as sns; sns.set(style='white')
import pandas as pd
data = {'prop_tenure': [0.0, 0.0, 0.06, 0.38, 0.61, 0.01, 0.10, 0.04, 0.22],
'prop_12m': [0.0, 0.0, 0.06, 0.38, 0.61, 0.01, 0.10, 0.04, 0.22],
'prop_6m': [0.0, 0.0, 0.10, 0.25, 0.66, 0.02, 0.12, 0.04, 0.22]}
df = pd.DataFrame(data)
g = sns.pairplot(df)
g.map_lower(corrfunc)
plt.show()
顺便提一下,对于较新版本 (>0.11.0
) 中的 seaborn,上面的答案不再有效。但是你需要添加一个 hue=None
才能让它再次工作。
def corrfunc(x, y, hue=None, ax=None, **kws):
"""Plot the correlation coefficient in the top left hand corner of a plot."""
r, _ = pearsonr(x, y)
ax = ax or plt.gca()
ax.annotate(f'ρ = {r:.2f}', xy=(.1, .9), xycoords=ax.transAxes)
参考这个问题https://github.com/mwaskom/seaborn/issues/2307#issuecomment-702980853
我有以下数据:
prop_tenure prop_12m prop_6m
0.00 0.00 0.00
0.00 0.00 0.00
0.06 0.06 0.10
0.38 0.38 0.25
0.61 0.61 0.66
0.01 0.01 0.02
0.10 0.10 0.12
0.04 0.04 0.04
0.22 0.22 0.22
我正在做一个配对图,如下所示:
sns.pairplot(data)
plt.show()
不过,我想显示变量之间的相关系数,如果可能的话,还想显示每个变量的偏度和峰度。 你如何在 seaborn 中做到这一点?
据我所知,没有开箱即用的功能可以执行此操作,您必须
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
def corrfunc(x, y, ax=None, **kws):
"""Plot the correlation coefficient in the top left hand corner of a plot."""
r, _ = pearsonr(x, y)
ax = ax or plt.gca()
ax.annotate(f'ρ = {r:.2f}', xy=(.1, .9), xycoords=ax.transAxes)
使用您输入的示例:
import seaborn as sns; sns.set(style='white')
import pandas as pd
data = {'prop_tenure': [0.0, 0.0, 0.06, 0.38, 0.61, 0.01, 0.10, 0.04, 0.22],
'prop_12m': [0.0, 0.0, 0.06, 0.38, 0.61, 0.01, 0.10, 0.04, 0.22],
'prop_6m': [0.0, 0.0, 0.10, 0.25, 0.66, 0.02, 0.12, 0.04, 0.22]}
df = pd.DataFrame(data)
g = sns.pairplot(df)
g.map_lower(corrfunc)
plt.show()
顺便提一下,对于较新版本 (>0.11.0
) 中的 seaborn,上面的答案不再有效。但是你需要添加一个 hue=None
才能让它再次工作。
def corrfunc(x, y, hue=None, ax=None, **kws):
"""Plot the correlation coefficient in the top left hand corner of a plot."""
r, _ = pearsonr(x, y)
ax = ax or plt.gca()
ax.annotate(f'ρ = {r:.2f}', xy=(.1, .9), xycoords=ax.transAxes)
参考这个问题https://github.com/mwaskom/seaborn/issues/2307#issuecomment-702980853