matplotlib - FigureとAxes
このトピックを終えると
matplotlibのFigure/Axes構造を理解し、基本的なグラフを自分で描画できるようになります。
matplotlibとは
matplotlibは、Pythonでグラフとチャートを描画するためのライブラリです。データを視覚的に見ると、単なる数値を見るよりもパターンがはるかにわかりやすくなります。
python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]
plt.plot(x, y)plt.show()pltは、matplotlib.pyplotの慣例的な省略形です。
FigureとAxes
matplotlibの基本的な構造は2つです。
text
Figure (キャンバス)
└── Axes (グラフ領域)
├── x軸
├── y軸
├── タイトル
└── データ (線、棒、点...)- Figure: 全体の図の領域。キャンバス。
- Axes: 実際のグラフが描画される空間。1つのFigureに複数のAxesを配置できます。
python
import matplotlib.pyplot as plt
# FigureとAxesを明示的に作成fig, ax = plt.subplots()
ax.plot([1, 2, 3], [10, 20, 30])ax.set_title("My First Plot")ax.set_xlabel("X axis")ax.set_ylabel("Y axis")
plt.show()plt.subplots()は、FigureとAxesを同時に作成します。この方法が最も推奨されます。
折れ線グラフ (Line Plot)
時間の経過に伴う変化を示すために使用します。
python
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]sales = [100, 120, 90, 150, 130]
fig, ax = plt.subplots(figsize=(8, 5))ax.plot(months, sales, marker="o", color="blue", linewidth=2)ax.set_title("Monthly Sales")ax.set_ylabel("Sales")ax.grid(True, alpha=0.3)
plt.show()marker="o": 各データポイントに円を表示figsize=(8, 5): 幅8インチ、高さ5インチgrid(True): グリッドを表示
棒グラフ (Bar Chart)
カテゴリ別の比較に使用します。
python
import matplotlib.pyplot as plt
languages = ["Python", "JS", "Java", "C++"]users = [30, 25, 20, 15]
fig, ax = plt.subplots()ax.bar(languages, users, color=["#3776AB", "#F7DF1E", "#B07219", "#00599C"])ax.set_title("Programming Language Popularity")ax.set_ylabel("Users (%)")
plt.show()ax.bar()にカラーリストを渡すと、各棒に異なる色を指定できます。
散布図 (Scatter Plot)
2つの変数間の関係を示します。
python
import matplotlib.pyplot as pltimport numpy as np
np.random.seed(42)x = np.random.randn(50)y = 2 * x + np.random.randn(50) * 0.5
fig, ax = plt.subplots()ax.scatter(x, y, alpha=0.7, color="coral")ax.set_title("Scatter Plot Example")ax.set_xlabel("X")ax.set_ylabel("Y")
plt.show()alpha=0.7は透明度です。点がたくさん重なる場合に役立ちます。
複数のグラフを同時に表示
python
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# 1つ目: 折れ線グラフaxes[0].plot([1, 2, 3], [1, 4, 9])axes[0].set_title("Line")
# 2つ目: 棒グラフaxes[1].bar(["A", "B", "C"], [5, 3, 7])axes[1].set_title("Bar")
# 3つ目: 散布図axes[2].scatter([1, 2, 3, 4], [4, 1, 3, 2])axes[2].set_title("Scatter")
plt.tight_layout()plt.show()plt.subplots(1, 3)は、1行3列のサブプロットを作成します。tight_layout()は、グラフ間の重なりを自動的に調整します。
保存
python
# 画面に表示する代わりに、ファイルに保存fig.savefig("chart.png", dpi=150, bbox_inches="tight")dpi=150: 解像度 (デフォルトは100)bbox_inches="tight": 余白を自動的に調整- サポートされている形式: PNG, PDF, SVG, JPG