Seabornで美しいグラフ表示-FaceGridのTutorialをやってみよう!
kaggleでコードを学習しているとグラフの表示でSeabornを使っている事が多いので、せっかくなのでしっかりSeabornを学習してみようと思う。
Seaborn
Seabornはmatplotlibに基づくPythonのデータ視覚化ライブラリです。 魅力的で有益な統計的なグラフィックスを描くための高水準のインターフェースを提供します。
https://seaborn.pydata.org/
matplotlibの機能をより美しく、より簡単にグラフを描く事ができるラッパー的な存在のようですね。
では、Seabornをインストールします。
pip install seaborn
今回はkaggleで頻出していたSeabornのFaceGridをチュートリアルから学習していきます。
チュートリアルを見ると、numpy、pandas、matplotlib、scipyをimportする必要があるのでまだ入れてなかったらインストール。
pip install numpy pip install pandas pip install matplotlib pip install scipy
FaceGridの引数
class = seaborn.FacetGrid(data,row = None,col = None,hue =None,col_wrap = None,sharex = true,sharey = True,height = 3,aspect = 1,palette =None,row_order =None,col_order =None,hue_order =None,hue_kws =None,dropna = True,legend_out = True,despine = True,margin_titles = False,xlim =None,ylim =None,subplot_kws =None,gridspec_kws =None,size =None)
data:DataFrame
各列が変数であり各行が観測値である、きちんとしたデータフレーム
row,col,hue
データのサブセットを定義する変数。グリッド内に描画される。
・メソッド
_init __(data [、row、col、hue、col_wrap、...])
matplotlib FigureとFacetGridオブジェクトを初期化。
add_legend([legend_data、title、label_order])
凡例を描画します。凡例を軸の外に置き、図のサイズを変更。
map(func、* args、** kwargs)
各ファセットのデータのサブセットにプロット関数を適用。
map_dataframe(func、* args、** kwargs)
.mapと似ているが、argsを文字列として渡し、kwargsにデータを挿入。
set(** kwargs)
各サブプロットAxesの属性を設定。
set_axis_labels([x_var、y_var])
グリッドの左列と下列に軸ラベルを設定。
set_titles([template、row_template、...])
各ファセットまたはグリッドマージンの上にタイトルを描画。
set_xlabels([label])
グリッドの一番下の行にx軸にラベルを付ける。
set_xticklabels([labels、step])
グリッドの一番下の行にx軸目盛のラベルを設定。
set_ylabels([label])
グリッドの左欄のy軸にラベルを付ける。
set_yticklabels([labels])
グリッドの左欄にy軸目盛のラベルを設定。
お会計(total_bill)と喫煙者と非喫煙者のランチ、ディナータイムのデータからグラフを描写
単変数のプロットを描く
import seaborn as sns;sns.set(style='ticks',color_codes=True) import matplotlib.pyplot as plt tips=sns.load_dataset('tips') g=sns.FacetGrid(tips,col='time',row='smoker') g=g.map(plt.hist,'total_bill')
追加のキーワード引数をマップ関数に渡し描く
import numpy as np bins=np.arange(0,65,5) g=sns.FacetGrid(tips,col='time',row='smoker') g=g.map(plt.hist,'total_bill',bins=bins,color='r')
g=sns.FacetGrid(tips,col='time',row='smoker') g=g.map(plt.scatter,'total_bill','tip',edgecolor='w')
変数の1つのプロット要素に色を割り当てる
g = sns.FacetGrid(tips, col="time", hue="smoker") g = (g.map(plt.scatter, "total_bill", "tip", edgecolor="w") .add_legend())
g = sns.FacetGrid(tips, col="day", height=4, aspect=.5) g = g.map(plt.hist, "total_bill", bins=bins)
g = sns.FacetGrid(tips, col="smoker", col_order=["Yes", "No"]) g = g.map(plt.hist, "total_bill", bins=bins, color="m")
別のカラーパレットを使用
kws = dict(s=50, linewidth=.5, edgecolor="w") g = sns.FacetGrid(tips, col="sex", hue="time", palette="Set1",hue_order=["Dinner", "Lunch"]) g = (g.map(plt.scatter, "total_bill", "tip", **kws) .add_legend())
カラーのマッピングに辞書を使用する
pal = dict(Lunch="seagreen", Dinner="gray") g = sns.FacetGrid(tips, col="sex", hue="time", palette=pal,hue_order=["Dinner", "Lunch"]) g = (g.map(plt.scatter, "total_bill", "tip", **kws).add_legend())
色ごとにマーカーを変えて見る
g = sns.FacetGrid(tips, col="sex", hue="time", palette=pal,hue_order=["Dinner", "Lunch"],hue_kws=dict(marker=["^", "v"])) g = (g.map(plt.scatter, "total_bill", "tip", **kws).add_legend())
Seabornはmatplotlibと比べて簡単にグラフを描く事ができるのでとても便利ですね😄