mcpField
A
alterlab-matplotlib

alterlab-matplotlib

github.com/alterlab-ieuデータ・データベース7872 回インストール5 週間前に更新
リポジトリ

alterlab-matplotlib について

Matplotlib を使う研究者や開発者向けに、静的・アニメーション・インタラクティブな可視化の方法を案内するスキルです。pyplot とオブジェクト指向 API、図のスタイルや出力に加え、実行可能な補助スクリプトも含みます。

主な機能

  1. 01静的・アニメーション・対話型プロット
  2. 02pyplot とオブジェクト指向 API
  3. 03複数パネルの図レイアウト
  4. 04スタイル・カラーマップ・注釈の調整
  5. 05PNG・PDF・SVG への出力
  6. 06プロットテンプレートとスタイルスクリプト

活用シーン

  1. 01科学・統計グラフの作成
  2. 02複数のサブプロットを含む図の作成
  3. 03図のスタイル調整と出版用ファイルの出力
  4. 04Jupyter や GUI アプリでのプロット利用

インストール

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

$npx skills add https://github.com/alterlab-ieu/alterlab-academic-skills --skill alterlab-matplotlib

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

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

evals/
evals.json
references/
api_reference.md
common_issues.md
plot_types.md
styling_guide.md
scripts/
plot_template.py
style_configurator.py

詳細

Matplotlib

概要

Matplotlib は、静的、アニメーション、インタラクティブなプロットを作成するための、Python の基盤となる可視化ライブラリです。このスキルでは、pyplot インターフェイス(MATLAB 形式)とオブジェクト指向 API(Figure/Axes)の両方を対象に、matplotlib を効果的に使用するための指針と、出版品質の可視化を作成するためのベストプラクティスを説明します。

このスキルを使用する場面

次のような場合に、このスキルを使用してください。

  • あらゆる種類のプロットやチャート(折れ線、散布図、棒グラフ、ヒストグラム、ヒートマップ、等高線図など)を作成するとき
  • 科学的または統計的な可視化を生成するとき
  • プロットの見た目(色、スタイル、ラベル、凡例)をカスタマイズするとき
  • サブプロットを使って複数パネルの図を作成するとき
  • 可視化をさまざまな形式(PNG、PDF、SVG など)でエクスポートするとき
  • インタラクティブなプロットやアニメーションを作成するとき
  • 3D 可視化を扱うとき
  • Jupyter ノートブックや GUI アプリケーションにプロットを組み込むとき
該当しないケース
シナリオ代わりに使用
DataFrame からすぐに統計プロットを作成する(自動的な CI を含む箱ひげ図/バイオリンプロット/ペアプロット/回帰プロット)alterlab-seaborn
ホバーやズームに対応するインタラクティブなチャート、単独で動作する HTML、または Dash ダッシュボードalterlab-plotly
論文投稿用の図:段組み幅、Okabe-Ito パレット、パネルラベル、有意差を示すアスタリスクalterlab-scientific-viz
完成した図のラベルの重なりや切れ、および 300 dpi でのエクスポートを確認するalterlab-figure-qa
データをプロットするものではなく、フローチャート、経路図、またはアーキテクチャ図を作成するalterlab-scientific-schematics

基本概念

Matplotlib の階層構造

Matplotlib は、オブジェクトの階層構造を使用します。

  1. Figure - すべてのプロット要素を格納する最上位のコンテナー
  2. Axes - データを表示する実際の描画領域(1 つの Figure に複数の Axes を含めることができます)
  3. Artist - 図上に表示されるすべての要素(線、テキスト、目盛りなど)
  4. Axis - 目盛りとラベルを処理する数直線オブジェクト(x 軸、y 軸)
2 つのインターフェイス

1. pyplot インターフェイス(暗黙的、MATLAB 形式)

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()
  • 手早くシンプルなプロットを作成するのに便利です
  • 状態を自動的に管理します
  • インタラクティブな作業やシンプルなスクリプトに適しています

2. オブジェクト指向インターフェイス(明示的)

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
ax.set_ylabel('some numbers')
plt.show()
  • ほとんどの用途で推奨されます
  • Figure と Axes をより明示的に制御できます
  • 複数のサブプロットを含む複雑な図に適しています
  • 保守やデバッグが容易です

一般的なワークフロー

1. 基本的なプロットの作成

単一プロットのワークフロー:

import matplotlib.pyplot as plt
import numpy as np

# Create figure and axes (OO interface - RECOMMENDED)
fig, ax = plt.subplots(figsize=(10, 6))

# Generate and plot data
x = np.linspace(0, 2*np.pi, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')

# Customize
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Trigonometric Functions')
ax.legend()
ax.grid(True, alpha=0.3)

# Save and/or display
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.show()
2. 複数のサブプロット

サブプロットのレイアウトを作成する:

# Method 1: Regular grid
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
axes[0, 0].plot(x, y1)
axes[0, 1].scatter(x, y2)
axes[1, 0].bar(categories, values)
axes[1, 1].hist(data, bins=30)

# Method 2: Mosaic layout (more flexible)
fig, axes = plt.subplot_mosaic([['left', 'right_top'],
                                 ['left', 'right_bottom']],
                                figsize=(10, 8))
axes['left'].plot(x, y)
axes['right_top'].scatter(x, y)
axes['right_bottom'].hist(data)

# Method 3: GridSpec (maximum control)
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :])  # Top row, all columns
ax2 = fig.add_subplot(gs[1:, 0])  # Bottom two rows, first column
ax3 = fig.add_subplot(gs[1:, 1:])  # Bottom two rows, last two columns
3. プロットの種類と用途

折れ線プロット - 時系列、連続データ、傾向

ax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue')

散布図 - 変数間の関係、相関

ax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')

棒グラフ - カテゴリの比較

ax.bar(categories, values, color='steelblue', edgecolor='black')
# For horizontal bars:
ax.barh(categories, values)

ヒストグラム - 分布

ax.hist(data, bins=30, edgecolor='black', alpha=0.7)

ヒートマップ - 行列データ、相関

im = ax.imshow(matrix, cmap='coolwarm', aspect='auto')
plt.colorbar(im, ax=ax)

等高線図 - 2D 平面上の 3D データ

contour = ax.contour(X, Y, Z, levels=10)
ax.clabel(contour, inline=True, fontsize=8)

箱ひげ図 - 統計的分布

# 'tick_labels' replaced 'labels' in matplotlib 3.9 (old name removed in 3.11)
ax.boxplot([data1, data2, data3], tick_labels=['A', 'B', 'C'])

バイオリンプロット - 分布の密度

ax.violinplot([data1, data2, data3], positions=[1, 2, 3])

プロットの種類やバリエーションに関する詳細な例については、references/plot_types.md を参照してください。

4. スタイルとカスタマイズ

色の指定方法:

  • 色名:'red'、'blue'、'steelblue'
  • 16 進コード:'#FF5733'
  • RGB タプル:(0.1, 0.2, 0.3)
  • カラーマップ:cmap='viridis'、cmap='plasma'、cmap='coolwarm'

スタイルシートの使用:

plt.style.use('seaborn-v0_8-darkgrid')  # Apply predefined style
# Available styles: 'ggplot', 'bmh', 'fivethirtyeight', etc.
print(plt.style.available)  # List all available styles

rcParams によるカスタマイズ:

plt.rcParams['font.size'] = 12
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['axes.titlesize'] = 16
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['legend.fontsize'] = 12
plt.rcParams['figure.titlesize'] = 18

テキストと注釈:

ax.text(x, y, 'annotation', fontsize=12, ha='center')
ax.annotate('important point', xy=(x, y), xytext=(x+1, y+1),
            arrowprops=dict(arrowstyle='->', color='red'))

スタイル設定の詳細やカラーマップのガイドラインについては、references/styling_guide.md を参照してください。

5. 図の保存

さまざまな形式にエクスポートする:

# High-resolution PNG for presentations/papers
plt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')

# Vector format for publications (scalable)
plt.savefig('figure.pdf', bbox_inches='tight')
plt.savefig('figure.svg', bbox_inches='tight')

# Transparent background
plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)

重要なパラメーター:

  • dpi:解像度(出版用は 300、ウェブ用は 150、画面表示用は 72)
  • bbox_inches='tight':余分な余白を取り除きます
  • facecolor='white':背景を白にします(透明テーマで便利です)
  • transparent=True:背景を透明にします
6. 3D プロットの操作
# projection='3d' auto-registers the 3D axes; no Axes3D import needed
# (the old `from mpl_toolkits.mplot3d import Axes3D` is a no-op on modern matplotlib).
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Surface plot
ax.plot_surface(X, Y, Z, cmap='viridis')

# 3D scatter
ax.scatter(x, y, z, c=colors, marker='o')

# 3D line plot
ax.plot(x, y, z, linewidth=2)

# Labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

ベストプラクティス

1. インターフェースの選択
  • 本番コードではオブジェクト指向インターフェース(fig, ax = plt.subplots())を使用します
  • pyplot インターフェースは、手軽な対話型の探索のみに使用します
  • 暗黙的な状態に頼らず、常に Figure を明示的に作成します
2. Figure のサイズと DPI
  • 作成時に figsize を設定します:fig, ax = plt.subplots(figsize=(10, 6))
  • 出力媒体に適した DPI を使用します:
    • 画面/ノートブック:72-100 dpi
    • Web:150 dpi
    • 印刷/出版物:300 dpi
3. レイアウトの管理
  • 要素の重なりを防ぐため、constrained_layout=True または tight_layout() を使用します
  • 自動的に間隔を調整するには、fig, ax = plt.subplots(constrained_layout=True) を推奨します
4. カラーマップの選択
  • 逐次型(viridis、plasma、inferno):一貫した推移のある順序付きデータ
  • 発散型(coolwarm、RdBu):意味のある中心点(例:ゼロ)があるデータ
  • 定性型(tab10、Set3):カテゴリ/名義データ
  • レインボーカラーマップ(jet)は知覚的に均一ではないため、避けてください
5. アクセシビリティ
  • 色覚多様性に配慮したカラーマップ(viridis、cividis)を使用します
  • 棒グラフでは、色に加えてパターン/ハッチングを追加します
  • 要素間に十分なコントラストを確保します
  • 説明的なラベルと凡例を含めます
6. パフォーマンス
  • 大規模なデータセットでは、プロットのファイルサイズを削減するため、呼び出し時に rasterized=True を使用します
  • プロットする前に、適切なデータ削減(例:密な時系列データのダウンサンプリング)を行います
  • アニメーションでは、パフォーマンス向上のために blitting を使用します
7. コードの整理
# Good practice: Clear structure
def create_analysis_plot(data, title):
    """Create standardized analysis plot."""
    fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)

    # Plot data
    ax.plot(data['x'], data['y'], linewidth=2)

    # Customize
    ax.set_xlabel('X Axis Label', fontsize=12)
    ax.set_ylabel('Y Axis Label', fontsize=12)
    ax.set_title(title, fontsize=14, fontweight='bold')
    ax.grid(True, alpha=0.3)

    return fig, ax

# Use the function
fig, ax = create_analysis_plot(my_data, 'My Analysis')
plt.savefig('analysis.png', dpi=300, bbox_inches='tight')

クイックリファレンススクリプト

このスキルには、scripts/ ディレクトリに実行可能なヘルパースクリプトが含まれています。直接実行して Figure またはスタイルシートを作成するか、上記のパターンを示す実例として参照してください。実行には matplotlib>=3.9 と numpy が必要です(ヒストグラムの例では scipy も必要です)。

plot_template.py

plots_template.py を実行すると、サポートされている任意のプロットタイプ(line、scatter、bar、histogram、heatmap、contour、box、violin、3d、または GridSpec のモンタージュとしての all)を描画できます。各 create_* ヘルパーは任意の ax= を受け取るため、独自の複数パネルレイアウトを構成できます。

# Render the full montage at 300 DPI
python scripts/plot_template.py --plot-type all --output figure.png
# Single plot type
python scripts/plot_template.py --plot-type scatter --output scatter.png
style_configurator.py

style_configurator.py を実行すると、スタイルプリセット(publication、presentation、web、dark、minimal)をプレビューし、再利用可能な .mplstyle ファイルとしてエクスポートできます。

python scripts/style_configurator.py --list                    # show presets
python scripts/style_configurator.py --preset publication \
    --output my_style.mplstyle                                 # export style sheet
python scripts/style_configurator.py --preset publication --preview

詳細リファレンス

包括的な情報については、次のリファレンスドキュメントを参照してください。

  • references/plot_types.md - コード例とユースケースを含む、プロットタイプの完全な一覧
  • references/styling_guide.md - スタイル設定、カラーマップ、カスタマイズの詳細
  • references/api_reference.md - コアクラスとメソッドのリファレンス
  • references/common_issues.md - よくある問題のトラブルシューティングガイド

他のツールとの連携

Matplotlib は次のツールと適切に連携します。

  • NumPy/Pandas - 配列や DataFrame から直接プロット
  • Seaborn - matplotlib を基盤とする高水準の統計的可視化
  • Jupyter - %matplotlib inline または %matplotlib widget による対話型プロット
  • GUI フレームワーク - Tkinter、Qt、wxPython アプリケーションへの埋め込み

よくある注意点

  1. 要素の重なり:constrained_layout=True または tight_layout() を使用します
  2. 状態の混乱:pyplot の状態機械に関する問題を避けるには、OO インターフェースを使用します
  3. 多数の図を扱う場合のメモリの問題:plt.close(fig) で図を明示的に閉じます
  4. フォントの警告:フォントをインストールするか、plt.rcParams['font.sans-serif'] で警告を抑制します
  5. DPI の混乱:figsize の単位はピクセルではなくインチです。pixels = dpi * inches
  6. 図番号の再利用(3.11+):図 1 が存在する場合、plt.subplots(num=1) または plt.subplot_mosaic(..., num=1) は ValueError を発生させます。clear=True を渡すか、fig.subplots() / fig.subplot_mosaic() で Axes を追加します。
  7. 3.11 で削除:matplotlib.cm.get_cmap(matplotlib.colormaps[name] を使用)、plot_date(datetime 値を指定して plot を呼び出す)、および boxplot の labels=(tick_labels= を使用)。
  8. 3.11 で非推奨(vert は警告後、3.13 で削除):boxplot / violinplot の vert=(orientation='horizontal' を使用。3.10 から利用可能)、contourf の出力に対する clabel(contour の線を重ねて、その線にラベルを付ける)、および Colormap.set_bad/set_under/set_over によるインプレース変更(cmap.with_extremes(bad=..., under=..., over=...) を使用)。

その他のリソース

コメント