Matplotlib 3次元の折れ線グラフ#

公開日

この記事では、Matplotlibで3次元の折れ線グラフをプロットする方法を解説します。2次元の折れ線グラフについては以下の記事を参照ください。

Matplotlibの折れ線グラフ

3次元折れ線グラフの基本#

plt.subplots()subplot_kwオプションに{'projection': '3d'}という辞書形式データを与えることで、3次元のプロットになります。折れ線グラフをプロットするには、さらにax.plot()メソッドを使います。ax.plot()に曲線が通過する点のx, y, z座標を配列で与えます。

以下の例では、曲線は(x, y, z)=(0 ,0, 0), (0, 1, 0), (1, 1, 1)の3点を通過します。

import matplotlib.pyplot as plt

x = [0, 0, 1]
y = [0, 1, 1]
z = [0, 0, 1]

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot(x, y, z)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/a6c001a261e4bb62cecf6c801da6eb45c150f5126c12edf495f0b58ccb979f88.png

Matplotlibの公式サイトによると、以下のようにplt.figure()fig.add_subplot()を組み合わせた方法が主流のようです。しかし、このサイトでは2次元のグラフと形式を揃えるため、基本的に上の記述方法で解説します。

fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(projection='3d')
ax.plot(x, y, z)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/a6c001a261e4bb62cecf6c801da6eb45c150f5126c12edf495f0b58ccb979f88.png

なお、projection='3d'とした場合、axAxes3DSubplotオブジェクトとなります。

print(type(ax))
<class 'matplotlib.axes._subplots.Axes3DSubplot'>

線の太さ・色・種類#

線の太さを変える場合、linewidthオプションで指定します。値が大きいほど、線が太くなります。 また、線の種類と色は、それぞれlinestyle, colorオプションで指定します。

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot(x, y, z, linewidth=5, color="black")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/f2d365e792bf760c0c46f70c84a8e50939ff161e3b5120e330174b41b24c5e15.png
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot(x, y, [1.0, 1.0, 1.0], linestyle="solid") # 実線(デフォルト)
ax.plot(x, y, [0.8, 0.8, 0.8], linestyle="dashed") # 破線
ax.plot(x, y, [0.6, 0.6, 0.6], linestyle="dashdot") # 一点鎖線
ax.plot(x, y, [0.4, 0.4, 0.4], linestyle="dotted") # 点線
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/632f674c68310dc0eef027ba835adc00a06587d8e1b190759e097a2f315faabf.png

linewidth, linestyleオプションの詳細は以下の記事を参考にして下さい。

Matplotlib 線の書式

また、colorオプションの詳細は以下の記事を参考にして下さい。

Matplotlib 色の書式

マーカーを表示する#

データのマーカーを表示するには、markerオプションを使用します。

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot(x, y, [1.0, 1.0, 1.0], marker="o")
ax.plot(x, y, [0.8, 0.8, 0.8], marker="v")
ax.plot(x, y, [0.6, 0.6, 0.6], marker="s")
ax.plot(x, y, [0.4, 0.4, 0.4], marker="+")
ax.plot(x, y, [0.2, 0.2, 0.2], marker="o")
ax.plot(x, y, [0.0, 0.0, 0.0], marker="D")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/d081541b095577e2241041dc7e6031cfc6e91f9670282de9971d37f565f24e15.png

主なmarkerオプションを以下の表に示します。

marker

説明

o

v

下向き三角

^

上向き三角

<

左向き三角

>

右向き三角

s

四角形(square)

p

五角形(pentagon)

+

+記号

x

x記号

D

ダイヤモンド

その他に利用可能なマーカーの種類については、以下の公式ページを参照してください。

matplotlib.markers — Matplotlib documentation