Processing math: 100%

[matplotlib 3D] 40.トーラス(Torus)

matplotlib 3D

はじめに

matplotlib mplot3dによる3Dグラフでトーラスを作成する。

コード

from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
u=np.linspace(0,2*np.pi,100)
v=np.linspace(0,2*np.pi,100)
u,v=np.meshgrid(u,v)
a = 2
b = 9
X = (b + a*np.cos(u)) * np.cos(v)
Y = (b + a*np.cos(u)) * np.sin(v)
Z = a * np.sin(u)
fig = plt.figure(figsize=(6,6),dpi=130)
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
ax.set_zlim(-10,10)
ax.set_box_aspect((1,1,1))
ax.plot_surface(X, Y, Z,alpha=0.8, cmap=cm.Wistia)
fig.savefig("torus.png", dpi=130,bbox_inches = 'tight',transparent=True)
plt.show()
view raw torus.py hosted with ❤ by GitHub

解説

モジュールのインポート

from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
view raw torus.py hosted with ❤ by GitHub

バージョン

#version
import matplotlib
print(matplotlib.__version__)
3.3.4
print(np.__version__)
1.20.1
view raw torus.py hosted with ❤ by GitHub

データの生成

u=np.linspace(0,2*np.pi,100)
v=np.linspace(0,2*np.pi,100)
u,v=np.meshgrid(u,v)
a = 2
b = 9
X = (b + a*np.cos(u)) * np.cos(v)
Y = (b + a*np.cos(u)) * np.sin(v)
Z = a * np.sin(u)
view raw torus.py hosted with ❤ by GitHub

トーラスは媒介変数でデータを生成するので、uとvを同じnp.linspace(0,2*np.pi,100)として、meshgrid化する。

トーラスは媒介変数で以下のようになる。ここでbはトーラス自体の大きい半径、aはトーラスの太さの半径となる。

x = (b+asin(u))cos(v)\\ y = (b+asin(u))sin(v)\\ z = asin(u)

3Dグラフの設定

v=np.linspace(0,2*np.pi,100)
u,v=np.meshgrid(u,v)
view raw torus.py hosted with ❤ by GitHub

軸範囲、軸ラベルの設定

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
ax.set_zlim(-10,10)
ax.set_box_aspect((1,1,1))
view raw torus.py hosted with ❤ by GitHub

3Dグラフの表示

ax.plot_surface(X, Y, Z,alpha=0.8, cmap=cm.Wistia)
view raw torus.py hosted with ❤ by GitHub

3Dグラフの保存

fig.savefig("torus.png", dpi=130,bbox_inches = 'tight',transparent=True)
view raw torus.py hosted with ❤ by GitHub
コードをダウンロード(.pyファイル)

コードをダウンロード(.ipynbファイル)

参考

A torus
The parametric description of a torus with radius $c$ and tube radius $a$ is\begin{align*}x &= (c + a\cos\theta) \cos\ph...

コメント