mcpField
S
seaborn

seaborn

github.com/tondevrelデータ・データベース25165 回インストール39 週間前に更新
リポジトリ

seaborn について

seaborn は、データ探索や統計グラフに使う Python の可視化ライブラリです。Pandas DataFrame を扱う分析向けに、高水準の作図やファセット機能を備え、Matplotlib と組み合わせて調整できます。

主な機能

  1. 01統計的な関係・分布プロット
  2. 02カテゴリ別の比較プロット
  3. 03不確実性を含む回帰プロット
  4. 04ヒートマップとクラスタ行列
  5. 05ファセットによる複数プロット
  6. 06テーマとカラーパレット

活用シーン

  1. 01データセット内の変数間関係の探索
  2. 02カテゴリごとの分布の比較
  3. 03信頼区間付きトレンドの可視化
  4. 04ヒートマップによる行列データの要約

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/tondevrel/scientific-agent-skills --skill seaborn

インストール後、Claude Code で/seabornを入力して読み込まれたか確認します。

詳細

Seaborn - 統計データ可視化

Seaborn を使うと、美しく情報量の多い統計プロットを通じて、データを探索し、理解できます。信頼区間の計算、データの集計、ファセットグリッドの作成といった複雑な作業を自動化します。

使用する場面

  • 複数の変数間の複雑な関係を可視化する場合(relplot)
  • 1 変量および 2 変量の分布を調べる場合(displot、kdeplot)
  • 統計的な要約を使ってカテゴリを比較する場合(catplot、boxplot、violinplot)
  • 線形回帰モデルとその不確実性を可視化する場合(regplot、lmplot)
  • 大規模な行列のヒートマップやクラスターマップを作成する場合
  • データのサブセットに基づく複数プロットのグリッドを構築する場合(FacetGrid)
  • Matplotlib の図に高水準の美的テーマを設定する場合

リファレンスドキュメント

公式ドキュメント:https://seaborn.pydata.org/
サンプルギャラリー:https://seaborn.pydata.org/examples/index.html
検索パターン:sns.load_dataset、sns.relplot、sns.catplot、sns.set_theme、sns.heatmap

基本原則

Figure-Level 関数と Axes-Level 関数
関数の種類例主な特徴
Figure-Levelrelplot、displot、catplot独自の図(FacetGrid)を作成します。サブプロット(col、row)に最適です。
Axes-Levelscatterplot、histplot、boxplot特定の ax にプロットします。Matplotlib のレイアウトとの統合に最適です。
Seaborn を使う場面
  • 統計分析や探索的データ分析(EDA)。
  • 「tidy」(ロング形式)で整理された Pandas DataFrame を直接扱う場合。
  • 95% 信頼区間(エラーバー)の自動計算。
  • ビジュアルテーマやカラーパレットをすばやく切り替える場合。
使用しない場面
  • 非常に低水準のカスタムグラフィックス(Matplotlib を使用してください)。
  • インタラクティブなウェブ可視化(Plotly を使用してください)。
  • 3D プロット(Matplotlib mplot3d または PyVista を使用してください)。
  • ネットワークグラフ(Matplotlib と組み合わせて NetworkX を使用してください)。

クイックリファレンス

インストール
pip install seaborn
標準的なインポート
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Apply the default theme
sns.set_theme()
基本パターン - tidy データのマッピング
import seaborn as sns

# Load an example dataset
tips = sns.load_dataset("tips")

# Create a scatter plot with semantic mapping
sns.relplot(
    data=tips,
    x="total_bill", y="tip", 
    hue="smoker", style="time", size="size",
)
plt.show()

重要なルール

✅ 推奨事項
  • tidy データを使用する - DataFrame が「ロング形式」(観測値ごとに 1 行)になっていることを確認します。
  • Figure-Level 関数を優先する - より適切なデフォルトレイアウトとファセット分割には、relplot/displot/catplot を使用します。
  • data= パラメーターを使用する - コードをすっきりさせるため、常に DataFrame を渡します。
  • テーマを設定する - スクリプトの早い段階で sns.set_theme(style="whitegrid", palette="muted") を使用します。
  • hue を活用する - セマンティックな色のマッピングを使って、2D プロットに追加の次元を加えます。
  • コンテキストに応じて使い分ける - 論文には sns.set_context("paper")、プレゼンテーションには "talk" を使用します。
❌ 非推奨事項
  • 1D 配列を手動で渡さない - sns.plot(x_array, y_array) は避けてください。Pandas との統合機能を活用できません。
  • インデックスを無視しない - Matplotlib とは異なり、Seaborn は DataFrame のインデックスをほとんど無視します(代わりに列を使用してください)。
  • プロットに情報を詰め込みすぎない - セマンティックなマッピング(hue、size、style)が多すぎると、グラフが読みづらくなります。
  • Matplotlib を忘れない - Seaborn 関数は Matplotlib オブジェクトを返します。調整には ax.set_title() を使用してください。

アンチパターン(絶対に避ける)

import seaborn as sns
import matplotlib.pyplot as plt

# ❌ BAD: Iterating through groups to plot manually
for s in df['species'].unique():
    subset = df[df['species'] == s]
    plt.scatter(subset['x'], subset['y'], label=s)

# ✅ GOOD: Let Seaborn handle grouping and legend
sns.scatterplot(data=df, x='x', y='y', hue='species')

# ❌ BAD: Mixing Seaborn and Matplotlib titles incorrectly
sns.displot(data=df, x='val')
plt.title("My Title") # ⚠️ Might apply to the wrong axis in a FacetGrid!

# ✅ GOOD: Use the returned object
g = sns.displot(data=df, x='val')
g.set_axis_labels("Value", "Count")
g.figure.suptitle("Correct Global Title", y=1.05)

関係性プロット(relplot)

散布図と折れ線グラフ
# Multi-faceted scatter plot
sns.relplot(
    data=tips, x="total_bill", y="tip",
    col="time", hue="day", style="sex",
    kind="scatter"
)

# Line plot with automatic aggregation (mean + 95% CI)
fmri = sns.load_dataset("fmri")
sns.relplot(
    data=fmri, x="timepoint", y="signal",
    hue="event", style="region",
    kind="line", errorbar="sd" # "sd" for standard deviation instead of CI
)

分布プロット(displot)

ヒストグラムと KDE
penguins = sns.load_dataset("penguins")

# Histogram with Kernel Density Estimate
sns.displot(data=penguins, x="flipper_length_mm", hue="species", kde=True)

# Bivariate distribution (Heatmap style)
sns.displot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", kind="kde")

# Empirical Cumulative Distribution (ECDF)
sns.displot(data=penguins, x="flipper_length_mm", hue="species", kind="ecdf")

カテゴリプロット(catplot)

カテゴリ内の比較と分布
# Boxplot (Show quartiles and outliers)
sns.catplot(data=tips, x="day", y="total_bill", kind="box")

# Violin plot (Show density and quartiles)
sns.catplot(data=tips, x="day", y="total_bill", hue="sex", kind="violin", split=True)

# Swarm plot (Show every point without overlap)
sns.catplot(data=tips, x="day", y="total_bill", kind="swarm")

# Bar plot (Show mean and error bars)
sns.catplot(data=tips, x="day", y="total_bill", kind="bar", errorbar=("pi", 95))

回帰プロット

線形トレンドの可視化
# Simple regression with scatter
sns.regplot(data=tips, x="total_bill", y="tip")

# Faceted regression
sns.lmplot(data=tips, x="total_bill", y="tip", col="smoker", hue="time")

# Logistic regression (for binary data)
sns.lmplot(data=df, x="variable", y="binary_outcome", logistic=True)

行列プロット

ヒートマップとクラスタリング
flights = sns.load_dataset("flights").pivot(index="month", columns="year", values="passengers")

# Heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(flights, annot=True, fmt="d", cmap="YlGnBu")

# Cluster map (Hierarchical clustering)
sns.clustermap(flights, standard_scale=1, cmap="mako")

グリッドオブジェクト(上級)

カスタムの複数プロットレイアウト
# JointPlot (Scatter + Marginals)
sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", kind="kde")

# PairPlot (All-against-all relations)
sns.pairplot(data=penguins, hue="species", corner=True)

# Custom FacetGrid
g = sns.FacetGrid(tips, col="time",  row="sex")
g.map(sns.scatterplot, "total_bill", "tip")

スタイルと美的表現

テーマとパレット
# Set overall look
sns.set_style("darkgrid") # white, dark, whitegrid, ticks
sns.set_context("talk")   # paper, notebook, talk, poster

# Custom palettes
sns.set_palette("husl") # Set global palette
my_pal = sns.color_palette("rocket", as_cmap=True) # Get palette as object

# Viewing a palette
sns.palplot(sns.color_palette("Set2"))

実践的なワークフロー

1. 探索的データ分析(EDA)のパイプライン
def initial_eda(df, target_col):
    """Generate basic visual summary of a dataset."""
    # 1. Distribution of target
    sns.displot(data=df, x=target_col, kde=True)
    
    # 2. Pairwise relations of numeric features
    sns.pairplot(data=df, hue=target_col if df[target_col].nunique() < 10 else None)
    
    # 3. Correlation heatmap
    plt.figure(figsize=(12, 10))
    sns.heatmap(df.corr(numeric_only=True), annot=True, cmap='coolwarm', fmt=".2f")

# initial_eda(iris, "species")
2. 科学的な結果の比較
def plot_experiment_results(df):
    """Plot results of an experiment with multiple conditions."""
    g = sns.catplot(
        data=df, kind="bar",
        x="condition", y="metric", hue="group",
        palette="viridis", alpha=.6, height=6
    )
    g.despine(left=True)
    g.set_axis_labels("Experimental Condition", "Accuracy (%)")
    g.legend.set_title("User Group")
    return g
3. カテゴリ別の時系列トレンド
def plot_trends(df, time_col, val_col, cat_col):
    """Visualizes trends over time with confidence intervals."""
    plt.figure(figsize=(12, 6))
    sns.lineplot(
        data=df, x=time_col, y=val_col, hue=cat_col,
        marker="o", err_style="bars"
    )
    plt.xticks(rotation=45)
    plt.tight_layout()

よくある落とし穴と解決策

プロットの外側に凡例を配置する
# ❌ Problem: Legend covers data in narrow plots
# ✅ Solution: Move legend manually using Matplotlib logic
g = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="day")
sns.move_legend(g, "upper left", bbox_to_anchor=(1, 1))
大規模データでのパフォーマンス低下
# ❌ Problem: sns.pairplot(large_df) hangs
# ✅ Solution: Sample data or use simpler plots
sns.pairplot(df.sample(1000), hue='category') 
# OR use hist instead of scatter
sns.jointplot(data=df, x='x', y='y', kind="hist")
ラベルの重なり
# ❌ Problem: Categorical labels on X-axis overlap
# ✅ Solution: Rotate labels using Matplotlib
g = sns.boxplot(data=df, x='very_long_category_name', y='value')
g.set_xticklabels(g.get_xticklabels(), rotation=45, horizontalalignment='right')

ベストプラクティス

  1. 整然データ形式を使用する - DataFrame がロング形式(観測値1つにつき1行)になっていることを確認します
  2. 図レベル関数を優先する - relplot、displot、catplot を使用すると、デフォルトのレイアウトやファセットがより適切になります
  3. 常に data= パラメーターを使用する - DataFrame を直接渡すことで、コードをすっきりと読みやすく保ちます
  4. テーマは早めに設定する - スタイルに一貫性を持たせるため、スクリプトの冒頭で sns.set_theme() を使用します
  5. セマンティックマッピングを活用する - hue、size、style を使用して、プロットに次元を追加します
  6. 適切なコンテキストを選ぶ - 論文には sns.set_context("paper")、プレゼンテーションには "talk" を使用します
  7. Seaborn は Matplotlib オブジェクトを返すことを覚えておく - 微調整には ax.set_title() のような Matplotlib のメソッドを使用します
  8. プロットに情報を詰め込みすぎない - 読みやすさを保つため、セマンティックマッピングは必要最小限にします
  9. ファセットには図レベル関数を使用する - サブプロットのレイアウトが自動的に処理されます
  10. 大規模なデータセットはサンプリングする - 大量のデータでのパフォーマンスを向上させるため、プロット前に df.sample() を使用します

Seaborn は、高レベルの抽象化によって美しい出版品質のグラフィックスを最小限の手間で作成できるため、統計的な可視化を楽しくしてくれます。

コメント