Matplotlibのワイヤーフレーム#

公開日

この記事では、Matplotlibでワイヤーフレームのグラフを出力する方法を解説します。ワイヤーフレームでは、点と点を結ぶ線で3次元の形状を表現します。

ワイヤーフレームの基本#

plt.subplots()subplot_kwオプションに{'projection': '3d'}という辞書形式データを与えることで、3次元のプロットになります。ワイヤーフレームとするには、さらにax.plot_wireframe()メソッドを使います。

ax.plot_wireframe()メソッドにはx, y, z座標を与えます。以下に例を示します。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 2*np.pi, 0.1)
y = np.arange(0, 4*np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.sin(Y)

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/58720e58ea959f0ddd161087f4a347499765041a51bd8a05922c6a4befc8cc52.png

なお、変数X, Y, Zはいずれも同じ大きさの2次元配列となります。

print(X.shape)
print(Y.shape)
print(Z.shape)
(126, 63)
(126, 63)
(126, 63)

ax.plot_wireframe()メソッドの主なオプションを以下に示します。

引数

説明

rcount, ccount

int

行・列方向の最大サンプル数。データ点数がこれより多い場合、ダウンサンプリングされる(デフォルト値:50)

rstride, cstride

int

ダウンサンプリングするときに飛ばすデータ点数

color

str

線の色

linewidth

float

線の太さ

alpha

float

線の透明度

rcountrstrideは片方のみ指定できます。同様に、ccountcstrideも片方のみ指定できます。

データのダウンサンプリング#

rcount, rstride, ccount, cstrideで描画する頂点の数を変更できます。

rcount=15, ccount=15として、描画点数をx, y軸方向にそれぞれ15点とした例を以下に示します。デフォルト値の50とした場合よりもメッシュが荒くなっていることが分かります。

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, rcount=15, ccount=15)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/ce94567728261ab910012efb0d360a05c2ada56a64e0465f7fea3f0675946abb.png

線の色#

colorオプションで線の色を指定できます。

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, color="green")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/a9b7e4611e532559bae3123b28486d9f30821775a6617f042d20c4f57d4192f5.png

指定可能な色については以下のページを参照下さい。

Matplotlib 色の書式

線の太さ#

linewidthsオプションで線の太さを指定できます。

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, linewidths=0.6)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/0bf12527a7450d8f91e603c811fa5dda81bbf5823c141ce795aa1fb6df02467e.png

線の透明度#

線の透明度を指定するには、alphaオプションを使用します。0から1の範囲の値を取り、値が小さいほど透明になります(デフォルトは1)。以下にalpha=0.3とした例を示します。

fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'})
ax.plot_wireframe(X, Y, Z, alpha=0.3)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
../_images/3740c57b427ed72b0ff114604bfb50e1b43391b15e47d66bbe30bd1fde1db54e.png