はじめに
簡単かつ簡潔にデータを可視化できるライブラリであるseabornを用いて、線形回帰つき散布図をregplot,lmplotで表示する方法について説明する。
コード


解説
モジュールのインポートなど
seabornなどのversion
データの読み込み
2017-2019のサッカーJリーグのJ1の結果を下記サイトから読み込む。URLごとにTableをDataFrameとして読み込み、読み込んだものをリストに加えていく。

リーグサマリー:2020 J1 順位表 | データによってサッカーはもっと輝く | Football LAB
フットボールラボ(Football LAB)はサッカーをデータで分析し、新しいサッカーの観戦方法を伝えるサッカー情報サイトです。選手のプレーを評価するチャンスビルディングポイントやプレースタイル指標、チームの戦術を評価するチームスタイル指標...
DataFrameへの列の追加と結合
各データフレームに[‘year’]の列を追加する。
pd.concatでリスト内のデータフレームを結合する。結合したDataFrameの上位5行は以下のようになる。
順位 | Unnamed: 1 | Unnamed: 2 | 勝点 | 試合数 | 勝 | 分 | 敗 | 得点 | 失点 | 得失 | 平均得点 | 平均失点 | year | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | NaN | 川崎フロンターレ川崎F | 72 | 34 | 21 | 9 | 4 | 71 | 32 | 39 | 2.1 | 0.9 | 2017 |
1 | 2 | NaN | 鹿島アントラーズ鹿島 | 72 | 34 | 23 | 3 | 8 | 53 | 31 | 22 | 1.6 | 0.9 | 2017 |
2 | 3 | NaN | セレッソ大阪C大阪 | 63 | 34 | 19 | 6 | 9 | 65 | 43 | 22 | 1.9 | 1.3 | 2017 |
3 | 4 | NaN | 柏レイソル柏 | 62 | 34 | 18 | 8 | 8 | 49 | 33 | 16 | 1.4 | 1.0 | 2017 |
4 | 5 | NaN | 横浜F・マリノス横浜FM | 59 | 34 | 17 | 8 | 9 | 45 | 36 | 9 | 1.3 | 1.1 | 2017 |
regplotの表示
x軸に”勝”データ, y軸に”得点”データをプロットし、線形回帰が表示される。

lmplotの表示
regplotと同様の線形回帰つき散布図がlmplotによっても表示される。

regplotとlmplotの違い
regplotはSeriesやnumpy配列を渡してもplotが表示されるが、lmplotはDataFrameのカラム名でなければならない。Seriesを渡した場合、TypeError Invalid comparison between dtype=int64 and strとなる。
jitterで散布図の位置をずらす
x_jitter=0.2と適当な数値をいれることで散布図の点を微妙にずらして、点が何個あるかが容易にわかるようになる。ずらすことによる線形回帰への影響はない。

x_estimator=np.meanで平均値を表示
x_estimator=np.meanとすることで散布図の代わりに平均値がプロットされる。

ci=noneで信頼区間を非表示にする
ci=noneで透明な青い部分として示されている信頼区間を非表示にすることができる。

hueで色によるデータの分離
hue=”year”とすることで年ごとに色を分けて散布図と線形回帰を表示できる。

col,rowで各データを複数グラフで表示
col=”year”とすることで横並びの図で各年の線形回帰つき散布図を示せる。

row=”year”とすることで縦並びの図で各年の線形回帰つき散布図を示せる。

参考
Estimating regression fits — seaborn 0.13.2 documentation
seaborn.regplot — seaborn 0.13.2 documentation
seaborn.lmplot — seaborn 0.13.2 documentation
コメント