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/2f24ace144dfe2318e6535510f38449cc14e92b57471d526fa03384861c0c1ed.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/a3bf19fe5f7b4f332e06b78db4c0e8e4aee5bb10eaff4f390d408d5a376f0824.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/eff3f106d2e22b28f936809d84633e89c2b4fba6d29bfcea79fecd9abfefa8ab.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/3fa2c93aae570430b4db17966b7e3a5b63b7d0f56487d1147f4d9786fc7b5a10.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/9b04435c7afbcc107bbbed9bf0b49f80940bc92781ce10f414fdf06ef4a3cc6c.png