matplotlib/seaborn
田中VPoE「可視化の原則がわかったところで、Pythonでグラフを作る方法を学ぼう。matplotlibが基盤で、seabornがその上に統計的な可視化機能を追加しているライブラリだ。」
あなた「2つのライブラリを使い分けるんですか?」
田中VPoE「seabornで手軽に統計的なグラフを作り、matplotlibで細かいカスタマイズをする。両方を組み合わせるのが実務的なアプローチだ。」
matplotlib基礎
基本構造
import matplotlib.pyplot as plt
import numpy as np
# Figure(キャンバス)と Axes(描画エリア)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y)
ax.set_title('タイトル')
ax.set_xlabel('X軸ラベル')
ax.set_ylabel('Y軸ラベル')
plt.tight_layout()
plt.show()
基本グラフの作成
折れ線グラフ
fig, ax = plt.subplots(figsize=(12, 5))
months = pd.date_range('2025-01', periods=12, freq='M')
sales = [4200, 3800, 4500, 4100, 4800, 5200, 4900, 5100, 5500, 4700, 5800, 7200]
ax.plot(months, sales, marker='o', linewidth=2, color='#2196F3', label='売上')
ax.axhline(y=np.mean(sales), color='gray', linestyle='--', alpha=0.5, label='平均')
ax.fill_between(months, sales, alpha=0.1, color='#2196F3')
ax.set_title('2025年 月次売上推移(万円)', fontsize=14, fontweight='bold')
ax.set_xlabel('月')
ax.set_ylabel('売上(万円)')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
棒グラフ
fig, ax = plt.subplots(figsize=(10, 6))
categories = ['家電', '書籍', '食品', 'ファッション', 'スポーツ']
values = [3200, 1800, 2500, 2100, 900]
colors = ['#2196F3' if v == max(values) else '#90CAF9' for v in values]
bars = ax.bar(categories, values, color=colors, edgecolor='white')
ax.bar_label(bars, fmt='%d万円', padding=3)
ax.set_title('カテゴリ別売上(最大カテゴリを強調)', fontsize=14)
ax.set_ylabel('売上(万円)')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.show()
ヒストグラム
fig, ax = plt.subplots(figsize=(10, 6))
ax.hist(df['amount'], bins=50, edgecolor='white', color='#2196F3', alpha=0.7)
ax.axvline(df['amount'].mean(), color='red', linestyle='--', label=f'平均: {df["amount"].mean():,.0f}円')
ax.axvline(df['amount'].median(), color='green', linestyle='--', label=f'中央値: {df["amount"].median():,.0f}円')
ax.set_title('注文金額の分布', fontsize=14)
ax.set_xlabel('注文金額(円)')
ax.set_ylabel('頻度')
ax.legend()
plt.tight_layout()
plt.show()
複数グラフの配置
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 左上:折れ線
axes[0, 0].plot(months, sales)
axes[0, 0].set_title('月次売上推移')
# 右上:棒グラフ
axes[0, 1].bar(categories, values)
axes[0, 1].set_title('カテゴリ別売上')
# 左下:ヒストグラム
axes[1, 0].hist(df['amount'], bins=30)
axes[1, 0].set_title('金額分布')
# 右下:散布図
axes[1, 1].scatter(df['age'], df['amount'], alpha=0.3)
axes[1, 1].set_title('年齢 vs 金額')
plt.tight_layout()
plt.show()
seaborn基礎
seabornはmatplotlibの上に構築された統計的可視化ライブラリです。
スタイル設定
import seaborn as sns
# テーマ設定
sns.set_theme(style='whitegrid', palette='muted', font_scale=1.1)
# 日本語フォント対応
plt.rcParams['font.family'] = 'IPAexGothic' # 環境に応じて変更
統計的なグラフ
箱ひげ図
fig, ax = plt.subplots(figsize=(10, 6))
sns.boxplot(data=df, x='category', y='amount', ax=ax)
ax.set_title('カテゴリ別注文金額の分布')
plt.tight_layout()
plt.show()
バイオリンプロット
fig, ax = plt.subplots(figsize=(10, 6))
sns.violinplot(data=df, x='category', y='amount', inner='quartile', ax=ax)
ax.set_title('カテゴリ別注文金額の分布(バイオリンプロット)')
plt.tight_layout()
plt.show()
ペアプロット
sns.pairplot(df[['amount', 'quantity', 'age', 'category']], hue='category', diag_kind='kde')
plt.suptitle('変数間の関係', y=1.02)
plt.show()
ヒートマップ(相関行列)
fig, ax = plt.subplots(figsize=(8, 6))
corr = df[['amount', 'quantity', 'age', 'pages_viewed']].corr()
sns.heatmap(corr, annot=True, cmap='RdBu_r', center=0, vmin=-1, vmax=1, ax=ax)
ax.set_title('相関行列')
plt.tight_layout()
plt.show()
カウントプロット
fig, ax = plt.subplots(figsize=(10, 5))
sns.countplot(data=df, x='category', hue='gender', ax=ax)
ax.set_title('カテゴリ別・性別別の注文数')
plt.tight_layout()
plt.show()
実務的なカスタマイズ
ビジネスレポート向けスタイル
def business_style(ax, title, subtitle=None):
"""ビジネスレポート向けのスタイル設定"""
ax.set_title(title, fontsize=14, fontweight='bold', loc='left', pad=20)
if subtitle:
ax.text(0, 1.05, subtitle, transform=ax.transAxes, fontsize=10, color='gray')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.grid(axis='y', alpha=0.3, linestyle='--')
fig, ax = plt.subplots(figsize=(12, 6))
ax.bar(categories, values, color='#1976D2')
business_style(ax, '3月以降、家電カテゴリが大幅成長', '2025年 カテゴリ別売上(万円)')
plt.tight_layout()
plt.show()
注釈の追加
ax.annotate(
'セール効果で急増',
xy=(months[11], 7200),
xytext=(months[9], 7500),
arrowprops=dict(arrowstyle='->', color='red'),
fontsize=11, color='red'
)
まとめ
| 項目 | ポイント |
|---|---|
| matplotlib | 基盤ライブラリ。Figure + Axesで構成。細かいカスタマイズが可能 |
| seaborn | 統計的グラフが簡単に作れる。boxplot、violinplot、pairplotなど |
| 使い分け | seabornで素早く作成、matplotlibで仕上げのカスタマイズ |
| ビジネス向け | 不要な装飾を排除、タイトルで結論を述べる、注釈で補足 |
チェックリスト
- matplotlibのFigure/Axes構造を理解している
- 折れ線、棒、ヒストグラム、散布図を作成できる
- seabornで箱ひげ図やヒートマップを作成できる
- ビジネスレポート向けにスタイルをカスタマイズできる
次のステップへ
matplotlib/seabornでの静的グラフ作成を学びました。次は、Plotlyを使ったインタラクティブな可視化を学びましょう。
推定読了時間:30分