Pythonでグラフを描画するときによく使われるライブラリに「Matplotlib」があります。
この記事では、学習の記録として、Matplotlibの基本的な使い方をまとめておきます。
✅ Matplotlibのインストール
まずは、ライブラリをインストールする必要があります。
pip install matplotlib
✅ 基本の流れ(共通の使い方)
Matplotlibでは、以下のような流れでグラフを描いていきます。
-
import matplotlib.pyplot as plt
で読み込む -
fig, ax = plt.subplots()
で図と軸(描画領域)を作る -
ax.plot()
などでグラフを描画 -
plt.show()
で表示
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [4, 5, 6]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Basic Line")
ax.set_xlabel("X軸")
ax.set_ylabel("Y軸")
plt.show()
(実行結果:基本的な折れ線グラフが表示されます)
✅ 折れ線グラフ(plot)
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
ax.plot(x, y)
ax.set_title("Line Graph")
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()
✅ 棒グラフ(bar)
fig, ax = plt.subplots()
labels = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
ax.bar(labels, values)
ax.set_title("Bar Graph")
ax.set_xlabel("Category")
ax.set_ylabel("Value")
plt.show()
✅ 円グラフ(pie)
import matplotlib.pyplot as plt
labels = ['Python', 'Java', 'C++', 'Ruby']
sizes = [40, 30, 20, 10]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart")
plt.show()
✅ 散布図(scatter)
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [5, 7, 4, 6, 8]
ax.scatter(x, y)
ax.set_title("Scatter Plot")
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()
✅ ヒストグラム(hist)
import numpy as np
data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=30)
ax.set_title("Histogram")
ax.set_xlabel("Value")
ax.set_ylabel("Frequency")
plt.show()
✅ 箱ひげ図(boxplot)
import numpy as np
data = [np.random.normal(0, 1, 100),
np.random.normal(1, 1.5, 100),
np.random.normal(2, 0.5, 100)]
fig, ax = plt.subplots()
ax.boxplot(data)
ax.set_title("Box Plot")
ax.set_xlabel("Group")
ax.set_ylabel("Value")
plt.show()
✅ 複数のグラフを並べる(複数Axes)
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [25, 16, 9, 4, 1]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot(x, y1)
ax1.set_title("Graph 1")
ax2.plot(x, y2)
ax2.set_title("Graph 2")
plt.tight_layout()
plt.show()
✅ グラフを画像として保存(savefig)
x = [1, 2, 3, 4]
y = [3, 7, 2, 9]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Save Graph")
plt.savefig("sample_graph.png") # カレントディレクトリに保存
plt.close()
✅ 軸の範囲を指定する(xlim / ylim)
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 6)
ax.set_ylim(0, 60)
ax.set_title("Set Axis Range")
plt.show()
✅ まとめ
- グラフの描画は基本的に
fig, ax = plt.subplots()
から始めると管理しやすい - グラフの種類には
plot
,bar
,pie
,scatter
,hist
,boxplot
などがある - 複数のグラフを並べたいときは
subplots()
を使って複数のax
を作る - グラフの保存は
savefig()
、軸調整はset_xlim()
,set_ylim()
今回はMatplotlibの基本グラフを一通りまとめました。
次回は凡例や色のカスタマイズ、スタイル設定なども学んでいきたいと思います。