PythonのMatplotlibで立体のグラフを作成してみます。
分布図
3次元の分布図を描いてみます。最もシンプルに書いてみました。
from matplotlib import pyplot as plt
xs = [0, 1, 2, 3]
ys = [0, 1, 4, 9]
zs = [0, 1, 8, 27]
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.scatter(xs, ys, zs)
plt.show()
xs = [0, 1, 2, 3]
ys = [0, 1, 4, 9]
zs = [0, 1, 8, 27]
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.scatter(xs, ys, zs)
plt.show()
x,y,zの座標をリスト(配列)で指定します。
このコードではxs,ys,zsにセットしています。この部分を書き換えれば最低限の立体分布図は作成できます。
ここではxは1乗、yは2乗、zは3乗の数をセットしています。
面白いのは描画した結果はマウス操作で見る角度を変えられることです。
下の図は上の図を真上から見たものです。横にx、縦にyで二次曲線になっていることが分かります。
点
連続した値を3Dグラフにします。
まず基本として点で表す場合です。
import matplotlib.pyplot as plt
import numpy as np
def func(x, y):
return np.sin(x) * np.sin(y)
xs = np.linspace(0, 10, 100)
ys = np.linspace(0, 10, 100)
xm, ym = np.meshgrid(xs, ys)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.scatter3D(xm, ym, func(xm,ym), s=0.5)
plt.show()
import numpy as np
def func(x, y):
return np.sin(x) * np.sin(y)
xs = np.linspace(0, 10, 100)
ys = np.linspace(0, 10, 100)
xm, ym = np.meshgrid(xs, ys)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.scatter3D(xm, ym, func(xm,ym), s=0.5)
plt.show()
xとyのsinの合計をzの値としています。
NumPyを使っています。
linspaceはrangeのNumPy版です。引数は最初の値、最後の値、個数となります。
meshgridは格子点を返します。
点なのでscatter3Dを使います。
ワイヤーフレーム
scatter3Dのところを次のようにします。
ax.plot_wireframe(xm, ym, func(xm,ym))
面
scatter3Dのところを次のようにします。
ax.plot_surface(xm, ym, func(xm,ym))
コメント