Seabornチートシート(目的のグラフ別早引き形式)【Python】

Pythonでのデータ可視化にはmatpltlibがよく使われますが、Seabornを使うことで、より見栄えの良いグラフを簡単に作成できます。本記事では、Seabornの使い方をサンプルコードを提供したグラフ別の早引き表形式で紹介し、目次から目的のグラフを検索できるようにしました。
seabornとは
Seabornは、Python用のデータ可視化ライブラリです。matplotlib
と比べて、美しいグラフを作ることが可能です。Rを使い慣れている方は、ggplotと似た見栄えのグラフが作成できるツールといえばわかりやすいかもしれません。私自身、ggplotっぽい綺麗なグラフをpythonで作りたくて探していたところ、Seabornにいきあたりました。
seabornのドキュメント:https://seaborn.pydata.org/index.html
インストール
pip
でインストール可能です。
pip install seaborn
Anaconda
を利用している場合は、以下のコマンドでインストールします。
conda install seaborn

Google Colabでは、標準でインストールされていました。
公式にあるように、Pythonで以下のコードを実行します。
import seaborn as sns
df = sns.load_dataset("penguins")
sns.pairplot(df, hue="species")
実行すると以下のようなグラフが表示されます。このように、なにも指定しなくても綺麗がグラフが作れるのがSeabornのメリットです。

もし、グラフが表示されない場合は、明示的に表示させる必要があります(matplotlib
が必要です)
import matplotlib.pyplot as plt
plt.show()
入力可能なデータ構造
Seabornでは、pandas, numpy, list, dictなどのほとんどのデータ形式を入力とすることができます。ただ、pandasのdataframe, seriesなどで入力するのが最も使いやすい印象です。
listで入力
pythonの組み込み型のlistで入力する場合の例です。
import seaborn as sns
import random
n = 100
x = [i for i in range(n)]
y = [random.randint(0,100) for _ in range(n)]
sns.scatterplot(x = x, y = y)
numpyで入力
numpyで入力する場合の例です。
import seaborn as sns
import random
import numpy as np
x = np.arange(0, 100)
y = np.random.randint(0, 100, 100)
sns.scatterplot(x=x, y=y)
pandasのデータフレームで入力
pandasで入力する場合の例です。x,yを生成するのに、numpyを使っています。
import seaborn as sns
import random
import numpy as np
import pandas as pd
x = np.arange(0, 100)
y = np.random.randint(0, 100, 100)
df = pd.DataFrame({'x': x, 'y': y})
sns.scatterplot(x='x', y='y', data=df)
なお、pandasを入力とした場合は、x軸、y軸にラベルがつきます。


グラフの種類
散布図(scatterplot
)
散布図は、scatterplot
関数で描画します。
size
オプションで点の大きさを指定できます。
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = np.random.randint(0, 100, 100)
df = pd.DataFrame({'x': x, 'y': y})
sns.scatterplot(x='x', y='y', data=df)

折れ線グラフ(lineplot
)
折れ線はlineplot
関数で描画します。
linewidth
で線の太さを指定できます
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y = np.random.randint(0, 100, 100)
df = pd.DataFrame({'x': x, 'y': y})
sns.lineplot(x='x', y='y', data=df)

折れ線(誤差範囲付き)グラフ
lineplot
関数で、1つのx値に対して複数のy値がある場合、エラーバンドを含んだプロットになります。
err_style="bars"
を設定すると誤差範囲がバーで表示されます
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randint(0, 100, 300)
y = x + np.random.normal(0, 10, 300)
df = pd.DataFrame({'x': x, 'y': y})
sns.lineplot(x='x', y='y', data=df)

複数の折れ線を1つのグラフにする
入力がデータフレームの場合は、それぞれの折れ線のラベル列をhue
に設定します(本来、hue
は色相の意味で、ここでは色分けを意味します)。
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
x = np.concatenate([x,x])
y = np.random.randint(0, 100, 200)
z = ['A' for _ in range(100)] + ['B' for _ in range(100)]
df = pd.DataFrame({'x': x, 'y': y, 'z' : z})
sns.lineplot(data=df, x='x', y='y', hue='z')

箱ひげ図(boxplot
)
箱ひげ図はboxplot
関数です
import seaborn as sns
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill",
hue="smoker", palette=["m", "g"],
data=tips)

棒グラフ(displot
)
棒グラフはdisplot
関数です。
bins
パラメータで、ビンの数を設定できます
import seaborn as sns
df = sns.load_dataset("penguins")
sns.displot(data = df, x="flipper_length_mm")

ヒストグラム(histplot
)
ヒストグラムはhistplot
です。
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm")

ヒストグラム(カーネル密度推定付き)
カーネル密度推定グラフを追加する場合は、kde=True
を設定します。
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm", kde=True)

カーネル密度推定グラフ(kdeplot
)
カーネル密度推定グラフだけを描画する場合は、kdeplot
関数を使います。
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.kdeplot(data=penguins, x="flipper_length_mm")

散布図行列グラフ(pairplot
)
seabornのグラフといえば、このイメージがあります。ペアプロット図です。pairplot
関数で作成します。
散布図行列は、複数のデータがある場合に2変数同士の組み合わせで散布図を作成し、行列にまとめたグラフです。データ分析に用いられるグラフで、データ間の関係が視覚的に確認しやすい点がポイントです。
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.pairplot(penguins, hue="species")

装飾など
複数のデータを同じグラフに表示する(hue
)
hue
オプションを利用します。
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm", hue='species', kde=True)

スタイルを変える(set_style
)
set_stype
を用いることでテーマを変更することができます。プリセットは5つ
darkgrid
whitegrid
dark
white
ticks
import seaborn as sns
sns.set_style("darkgrid")
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm", hue='species', kde=True)

- テーマサンプル(クリックで開きます)
-
darkgrid
whitegrid
dark
white
ticks
テーマを変える (set_theme
)
set_theme
を使うとスタイルとパレット、フォントなどを変更することができます。オプションが豊富なので、詳しくは公式ページを参考にしてください。
style
は、上で説明したスタイルを、palette
は、deep
, muted
, pastel
, bright
, dark
, colorblind
が設定できます。
import seaborn as sns
sns.set_theme(style="whitegrid", palette="pastel")
penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm", hue='species', kde=True)

グラフにタイトルをつける(set_title
)
グラフにタイトルをつける場合は、set_title
を使うことでタイトルをつけることができます。
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sns.set_theme(style="darkgrid", palette="dark")
x = np.random.randint(0, 100, 300)
y = x + np.random.normal(0, 10, 300)
df = pd.DataFrame({'x': x, 'y': y})
g = sns.lineplot(x='x', y='y', data=df)
g.set_title("random graph")

凡例を削除する
legend=False
を指定することで凡例を削除できます。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
x = np.arange(0, 100)
x = np.concatenate([x,x])
y = np.random.randint(0, 100, 200)
z = ['A' for _ in range(100)] + ['B' for _ in range(100)]
df = pd.DataFrame({'x': x, 'y': y, 'z' : z})
sns.lineplot(data=df, x='x', y='y', hue='z', legend=False)

ちょっと高度な使い方
.
で繋げて指示する
seabornではパイプラインみたいな感じで、.
で繋げることで指示を追加することができます。
例えば、上の「凡例を消す」の場合、以下のように記述することでも凡例を消すことができます。
sns.lineplot(data=df, x='x', y='y', hue='z').legend().remove()
seaborn.object
を使ったグラフ作成
Rのggplotっぽいインターフェースも実装されています。例えば、以下のようにすれば、折れ線に「点」を描画することもできます。

こちらの機能については別記事にまとめています

import seaborn.objects as so
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
x = np.arange(0, 100)
x = np.concatenate([x,x])
y = np.random.randint(0, 100, 200)
z = ['A' for _ in range(100)] + ['B' for _ in range(100)]
df = pd.DataFrame({'x': x, 'y': y, 'z' : z})
so.Plot(data=df, x='x', y='y', color='z').add(so.Dots()).add(so.Lines())

まとめ
seabornはかなり多機能です。今回は自分が利用する部分について解説しました。
seabornの場合、あまり調整しなくてもそれなりに綺麗なグラフを描画できるのがメリットですが、細かなオプションを設定することでさらに好みのグラフに仕上げることも可能です。