Python matplotlib完全ガイド – データ可視化の基礎から応用まで

 

Pythonでデータ可視化を行う際に最も広く使われているライブラリがmatplotlibです。科学計算、データ分析、機械学習プロジェクトにおいて、データの可視化は結果の理解や洞察の発見に欠かせません。この記事では、matplotlibの基本的な使い方から応用テクニックまで、実践的なサンプルコードとともに詳しく解説します。

matplotlibとは

matplotlibは、Pythonで2Dプロットを作成するためのライブラリです。MATLAB風のAPIを提供し、静的、アニメーション、インタラクティブな可視化を作成できます。NumPy、pandas、scikit-learnなど、Pythonのデータサイエンスエコシステムと密接に統合されています。

インストールと基本設定

インストール方法

pip install matplotlib

基本的なインポート

import matplotlib.pyplot as plt
import numpy as np

基本的なグラフの作成

1. 線グラフ(Line Plot)

最も基本的なグラフである線グラフの作成方法です。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()

2. 散布図(Scatter Plot)

データポイント間の関係を視覚化する散布図の作成方法です。

x = np.random.randn(50)
y = np.random.randn(50)
plt.scatter(x, y)
plt.show()

3. 棒グラフ(Bar Chart)

カテゴリ別のデータ比較に適した棒グラフの作成方法です。

categories = ['A', 'B', 'C', 'D']
values = [23, 17, 35, 29]
plt.bar(categories, values)
plt.show()

4. ヒストグラム(Histogram)

データの分布を視覚化するヒストグラムの作成方法です。

data = np.random.normal(0, 1, 1000)
plt.hist(data, bins=30)
plt.show()

グラフのカスタマイズ

タイトルとラベルの追加

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title('サンプルグラフ')
plt.xlabel('X軸')
plt.ylabel('Y軸')
plt.show()

色とスタイルの変更

plt.plot([1, 2, 3, 4], [1, 4, 2, 3], color='red', linestyle='--', marker='o')
plt.show()

複数の線を同じグラフに表示

x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend()
plt.show()

サブプロット(複数グラフの表示)

一つの図に複数のグラフを表示する方法です。

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot([1, 2, 3], [1, 4, 2])
ax1.set_title('グラフ1')
ax2.scatter([1, 2, 3], [2, 3, 1])
ax2.set_title('グラフ2')
plt.show()

高度な可視化テクニック

1. ヒートマップ

2次元データの可視化に効果的なヒートマップの作成方法です。

data = np.random.rand(10, 10)
plt.imshow(data, cmap='hot', interpolation='nearest')
plt.colorbar()
plt.show()

2. 3Dプロット

3次元データの可視化方法です。

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
ax.plot_surface(X, Y, Z)
plt.show()

3. アニメーション

動的なグラフの作成方法です。

import matplotlib.animation as animation

fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 100)
line, = ax.plot(x, np.sin(x))

def animate(frame):
    line.set_ydata(np.sin(x + frame/10))
    return line,

ani = animation.FuncAnimation(fig, animate, frames=100, blit=True)
plt.show()

pandasとの連携

pandasのDataFrameと組み合わせたデータ可視化の方法です。

import pandas as pd

df = pd.DataFrame({'x': range(10), 'y': np.random.randn(10)})
df.plot(x='x', y='y', kind='line')
plt.show()

スタイルとテーマ

matplotlibには多数の組み込みスタイルが用意されています。

plt.style.use('seaborn')  # または 'ggplot', 'classic'など
plt.plot([1, 2, 3], [1, 4, 2])
plt.show()

パフォーマンスの最適化

大量データの効率的な描画

# blittingを使用した高速描画
fig, ax = plt.subplots()
x = np.random.randn(10000)
y = np.random.randn(10000)
ax.scatter(x, y, alpha=0.5, s=1)
plt.show()

メモリ使用量の最適化

# 図を明示的に閉じてメモリを解放
plt.figure()
plt.plot([1, 2, 3], [1, 4, 2])
plt.savefig('output.png')
plt.close()  # メモリ解放

よくある問題と解決方法

日本語フォントの設定

plt.rcParams['font.family'] = 'DejaVu Sans'  # または適切な日本語フォント
plt.title('日本語タイトル')
plt.show()

図のサイズ調整

plt.figure(figsize=(12, 8))
plt.plot([1, 2, 3], [1, 4, 2])
plt.show()

軸の範囲設定

plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.xlim(0, 5)
plt.ylim(0, 5)
plt.show()

実践的な使用例

データ分析レポート用のグラフ

# 売上データの可視化例
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales = [120, 135, 148, 165, 142, 158]

plt.figure(figsize=(10, 6))
plt.plot(months, sales, marker='o', linewidth=2, markersize=8)
plt.title('月別売上推移', fontsize=16)
plt.xlabel('月', fontsize=12)
plt.ylabel('売上(万円)', fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

まとめ

matplotlibは柔軟で強力なデータ可視化ライブラリです。基本的な線グラフから複雑な3Dプロット、アニメーションまで幅広い表現が可能です。データサイエンスや機械学習プロジェクトにおいて、結果の可視化や洞察の発見に欠かせないツールとなっています。

この記事で紹介したテクニックを組み合わせることで、より効果的で美しいデータ可視化を実現できます。まずは基本的なグラフから始めて、徐々に高度な機能を習得していくことをお勧めします。

参考リンク

matplotlibを使いこなして、データから価値ある洞察を見つけ出しましょう。

■プロンプトだけでオリジナルアプリを開発・公開してみた!!

■AI時代の第一歩!「AI駆動開発コース」はじめました!

テックジム東京本校で先行開始。

■テックジム東京本校

「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。

<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。

<月1開催>放送作家による映像ディレクター養成講座

<オンライン無料>ゼロから始めるPython爆速講座