在熊猫的散布矩阵中添加回归线

时间:2019-12-13 16:08:39

标签: python pandas matplotlib scatter-matrix

关于这个主题,我发现了很多新闻,但是没有人提出我的理由。 我有一个很大的数据框,我想在其中添加回归线,并在网格的另一侧仅将相关系数放在空白处。

df=pd.DataFrame(np.concatenate(Arr))
df

a   b   c   d   e   f   g   h
0   94.122932   87.930649   57.192429   35.844883   57.971062   65.494003   52.297470   52.553162
1   92.231049   87.693893   53.804562   33.005547   52.124733   56.096642   48.072334   46.176899
2   89.846649   87.448158   49.858879   29.900572   46.716476   44.890785   44.026333   40.420742
3   87.181229   87.291374   46.363262   27.649641   41.478992   36.512981   40.489635   35.537495
4   85.915497   87.230659   43.459812   25.325624   37.368202   30.755083   37.228760   31.470888
...

axes = pd.plotting.scatter_matrix(df)
for i in range(np.shape(axes)[0]):
    for j in range(np.shape(axes)[1]):
        if i < j:
            axes[i,j].set_visible(False)

enter image description here

如何添加?

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用seaborn的PairGrid

from scipy.stats import pearsonr
def reg_coef(x,y,label=None,color=None,**kwargs):
    ax = plt.gca()
    r,p = pearsonr(x,y)
    ax.annotate('r = {:.2f}'.format(r), xy=(0.5,0.5), xycoords='axes fraction', ha='center')
    ax.set_axis_off()

iris = sns.load_dataset("iris")
g = sns.PairGrid(iris)
g.map_diag(sns.distplot)
g.map_lower(sns.regplot)
g.map_upper(reg_coef)

enter image description here