一覧へ

Seaborn — 宣言的な可視化

Seabornの宣言的な構文で、箱ひげ図、棒グラフ、ヒートマップをすばやく描く方法を学びます。

入門
|
10
|
検証済み (2026-07)
Seaborn宣言的な可視化箱ひげ図棒グラフmatplotlibとの比較
進捗0/17 (0%)

Seaborn — 宣言的な可視化

このトピックを終えると

Seaborn の宣言的な構文が matplotlib とどのように異なるかを理解し、箱ひげ図、棒グラフ、ヒートマップを 1 行で描画できるようになります。


matplotlib が使いづらくなる瞬間

matplotlib で「部署別の年収分布」を描画するには、次のようなコードが必要になります。

python
import matplotlib.pyplot as plt
import numpy as np
departments = df['department'].unique()
positions = range(len(departments))
fig, ax = plt.subplots()
for i, dept in enumerate(departments):
salaries = df[df['department'] == dept]['salary']
ax.boxplot(salaries, positions=[i], widths=0.6)
ax.set_xticks(positions)
ax.set_xticklabels(departments)
ax.set_ylabel('年収')
ax.set_title('部署別の年収分布')
plt.show()

ループを回してデータを分割し、位置を計算し、ラベルを手動で設定します。 Seaborn で同じグラフを:

python
import seaborn as sns
sns.boxplot(data=df, x='department', y='salary')
plt.show()

2 行です。 「何を表示するか」だけを記述すれば、残りのことは Seaborn が処理します。 これが **宣言的な(declarative)**構文です。


命令型 vs 宣言型

matplotlib (命令型)Seaborn (宣言型)
視点「どのように描画するか」を段階的に指示「何を表示するか」を宣言
データ分割ループ/フィルタリングを手動で実行自動 (x, y, hue)
色/凡例手動で指定自動生成
カスタマイズ非常に詳細ほとんど自動、詳細な場合は matplotlib

Seaborn は matplotlib を基盤としたラッパーです。 デフォルト設定で美しいグラフをすばやく作成し、詳細な調整が必要な場合は matplotlib を使用します。


主要なグラフ 5 種類

1. 分布 — histplot

python
sns.histplot(data=df, x='salary', bins=20, kde=True)

kde=True を追加すると、密度推定線(滑らかな曲線)が重ねて描画されます。

2. カテゴリ別の分布 — boxplot

python
sns.boxplot(data=df, x='department', y='salary')

中央値、四分位、外れ値を一目で確認できます。 部署間の年収の差を比較する場合に最も効果的です。

3. 個数カウント — countplot

python
sns.countplot(data=df, x='department', hue='gender')

各カテゴリの頻度を棒グラフで表示します。 hue を使用して性別などのサブカテゴリを追加すると、色で区別されます。

4. 関係 — scatterplot

python
sns.scatterplot(data=df, x='experience', y='salary', hue='department')

2 つの数値変数の関係を点で表示します。 経験と年収が比例するかどうかを一目で確認できます。

5. 相関関係 — heatmap

python
corr = df[['salary', 'experience', 'age']].corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', vmin=-1, vmax=1)

annot=True で数値を表示し、cmap でカラーパレットを指定します。 正の相関(赤)、負の相関(青)が色で区別されます。


hue — 3 番目の変数

Seaborn の最も強力な機能です。

python
# hue なし — 全体的な散布図
sns.scatterplot(data=df, x='experience', y='salary')
# hue を追加 — 部署ごとに色を区別
sns.scatterplot(data=df, x='experience', y='salary', hue='department')

hue は 3 番目の変数を 色でエンコードします。 matplotlib でこれを実行するには、ループを回して色を手動で指定する必要があります。 Seaborn は 1 つの単語で済みます。


スタイル設定

python
# 全体のスタイルを変更
sns.set_theme(style='whitegrid')
# パレットを変更
sns.set_palette('Set2')
# 個別のグラフで
sns.boxplot(data=df, x='dept', y='salary', palette='pastel')

スタイルオプション:

  • darkgrid — デフォルト、グレーの背景 + グリッド
  • whitegrid — 白い背景 + グリッド
  • dark — グリッドのないグレーの背景
  • white — シンプルな白い背景
  • ticks — 軸の目盛りのみ

Seaborn + matplotlib の組み合わせ

python
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.boxplot(data=df, x='dept', y='salary', ax=axes[0])
axes[0].set_title('部署別の年収')
sns.histplot(data=df, x='salary', bins=20, ax=axes[1])
axes[1].set_title('全体の年収分布')
plt.tight_layout()
plt.show()

ax パラメータを使用して、matplotlib の Axes に Seaborn グラフを配置できます。 レイアウトは matplotlib で、グラフの内容は Seaborn で — この組み合わせが実戦パターンです。


重要なポイント

Seaborn は 「何を表示するか」を宣言するだけ で、残りのことは自動的に描画する可視化ライブラリです。 hue という 1 つの単語で 3 番目の変数を色でエンコードする — これが Seaborn の主要な強みです。 迅速な探索には Seaborn、詳細な調整には matplotlib — 両方を使いこなせる必要があります。

💬 質問・コメント

0件のコメント

ログインせずに投稿できます。ゲスト投稿は投稿者自身で編集・削除できません。

0/2000

読み込み中...