0
0

Seabornのcatplotで引数にaxを渡してグラフを並べて表示させる方法

Posted at

はじめに

データ分析する際にSeabornを使用するのですが、グラフを並べて表示したいと思いました。
matplotlibではplt.subplotsを使用して1つのfigに複数のaxを入れることができ、seabornでも同様にしてできそうかと思ったのですが、catplotだけは簡単にできなかったので備忘録として書きます。

まずは結論

上記のリファレンスを読みseaborn.catplot(kind="swarm")だったらseaborn.swarmplot(ax=ax)にするだけ!!

詳しい説明

seabornでは基本的に、plotをする関数の引数のaxにmatplotlibで作成したaxを渡すだけで、図中にseabornで作成したグラフを入れることができます。

例えばkdeplot関数では、

import seaborn as sns
y = "列名" 
fig, axes = plt.subplots(2, 2, figsize=(2*1.4*3.8, 2*3.8),dpi=300, tight_layout=True, )
sns.kdeplot(hue="type", x=y, data=data, shade=False, ax=axes[0,0])

といったように引数にaxを追加して渡してやるだけでpltで作成したfigureにグラフを入れることができます。

しかし、catplot関数に同様に引数にaxを追加して渡してやっても反映されないという問題に遭遇しました。

いろいろ調べた結果、

stripplot() (with kind="strip"; the default)
swarmplot() (with kind="swarm")
boxplot() (with kind="box")
violinplot() (with kind="violin")
boxenplot() (with kind="boxen")
pointplot() (with kind="point")
barplot() (with kind="bar")
countplot() (with kind="count")
https://seaborn.pydata.org/generated/seaborn.catplot.html

上記のリファレンスのように、catplot関数のkindに与えている文字+plotという関数を代わりに使用してaxを使用すればいいということがわかりました。

なので、例えば2x2のグラフを表示させたい場合は、以下のように書くことができます。

    import pandas as pd
    import seaborn as sns
    
    data = pd.DataFrame()
    y = "列名" 
    
    fig, axes = plt.subplots(2, 2, figsize=(2*1.4*3.8, 2*3.8),dpi=300, tight_layout=True, )

    #sns.catplot(x="type" ,y=y, data=data, kind="swarm", ax=axes[0,0])
    sns.swarmplot(x="type" ,hue="type", y=y, data=data, legend=False, ax=axes[0,0])
    
    #sns.catplot(x="type" ,y=y, data=data, kind="bar", ax=axes[0,1])
    sns.barplot(x="type" ,y=y, data=data, ax=axes[0,1])
    
    #sns.catplot(x="type" ,y=y, data=data, kind="violin", ax=axes[1,0])
    sns.violinplot(x="type" ,y=y, data=data, ax=axes[1,0])
    
    sns.kdeplot(hue="type", x=y, data=data, shade=False, ax=axes[1,1])

    #fig.savefig("save" + ".png", format="png", dpi=300,transparent=True)
    plt.show()

最後に

今回はSeabornのcatplotで引数にaxを渡してグラフを並べて表示させる方法を解説しました。
調べても英語の情報ばかり出てきてよくわからなかったので、参考になればと思って書きました。
それでは楽しいデータ分析ライフを!

0
0
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
0
0