11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

seabornのpairplotをカスタムして相関係数を表示する(欠損値にも対応)

Posted at

seabornのpairplotは便利だが、相関係数も確認できればな・・・と思ったので作ってみた。
欠損値があってもwarningが出ないようにしている。

import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

def draw_hist(x, **kws):
    plt.hist(x[~np.isnan(x)])
    
def corr_func(x, y, **kws):
    mask = ~np.logical_or(np.isnan(x), np.isnan(y))
    x, y = x[mask], y[mask]
    r, _ = stats.pearsonr(x, y)
    ax = plt.gca()
    ax.annotate("r = {:.3f}".format(r),
               xy=(.2, .5), 
               xycoords=ax.transAxes,
               size=16)

def pairplot(df):
    g = sns.PairGrid(df, height=1.6, dropna=False)
    g.map_diag(draw_hist)
    g.map_upper(sns.regplot, scatter_kws={"s": 8}, line_kws={"color":  "r"})
    g.map_lower(corr_func)
from sklearn.datasets  import load_boston
boston = load_boston()
boston_df = pd.DataFrame(boston["data"],  columns=boston["feature_names"])

pairplot(boston_df.iloc[:,:6])

ちなみに、sns.heatmapでannot=Trueとすると値が表示されることに後から気づいた。まあ散布図と一緒に確認できるので。。

sns.heatmap(boston_df.iloc[:,:6].corr(), annot=True)

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?