[英]Rotation torus in matplotlib3d
最近我開始使用 matplotlib。 你能幫助我如何在 Oz 周圍旋轉(旋轉)animation 一個圓環嗎? 我嘗試在更新 function 中更改 x、y、z 的值,但這會更改圓環的位置,而不是其旋轉。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
t = np.linspace(0, 2 * np.pi, 50)
th, ph = np.meshgrid(t, t)
r = 0.4
x, y, z = 1.5*r * np.sin(ph), (2 + r * np.cos(ph)) * np.sin(th), (2 + r * np.cos(ph)) * np.cos(th)
Steps = 1001
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
plot=[ax.plot_surface(x, y, z+2,rstride=2,cstride=1,color='green',alpha=.5)]
ax.set(xlim=[-4, 4], ylim=[-4, 4], zlim=[0, 4])
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
a = 0.5 * np.outer(np.cos(u), np.sin(v))
b = 0.5 * np.outer(np.sin(u), np.sin(v))
c = 0.4 * np.outer(np.ones(np.size(u)), np.cos(v))
elev = 10.0
rot = 80.0 / 180 * np.pi
ax.plot_surface(a, b, c+4, rstride=4, cstride=4, color='b', linewidth=0)
theta = np.linspace(0, 20 * np.pi,1001)
ax.view_init(elev = elev, azim = 0)
def update(num):
plot[0].remove()
x, y, z = 1.5 * r * np.sin(ph), (2 + r * np.cos(ph)) * np.sin(th), (2 + r * np.cos(ph)) * np.cos(th)
plot[0] = ax.plot_surface(1.5 * r * np.sin(ph),(2 + r*np.cos(ph)) * np.sin(th),(z+2),rstride=2,cstride=1,color='green',alpha=.5)
ani = animation.FuncAnimation(fig, update, 100,interval=40)
ax.elev = 60
plt.show() ```
一種方法是在update
function 中ax.view_init
function 的azim
參數的值。 例如,您可以添加行ax.view_init(azim=360*num/100, elev=10)
。 這樣,視點在每一幀都圍繞 z 軸旋轉。 請參閱下面的完整代碼:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
t = np.linspace(0, 2 * np.pi, 50)
th, ph = np.meshgrid(t, t)
r = 0.4
x, y, z = 1.5*r * np.sin(ph), (2 + r * np.cos(ph)) * np.sin(th), (2 + r * np.cos(ph)) * np.cos(th)
Steps = 1001
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
plot=[ax.plot_surface(x, y, z+2,rstride=2,cstride=1,color='green',alpha=.5)]
ax.set(xlim=[-4, 4], ylim=[-4, 4], zlim=[0, 4])
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
a = 0.5 * np.outer(np.cos(u), np.sin(v))
b = 0.5 * np.outer(np.sin(u), np.sin(v))
c = 0.4 * np.outer(np.ones(np.size(u)), np.cos(v))
elev = 10.0
rot = 80.0 / 180 * np.pi
ax.plot_surface(a, b, c+4, rstride=4, cstride=4, color='b', linewidth=0)
theta = np.linspace(0, 20 * np.pi,1001)
ax.view_init(elev = elev, azim = 0)
def update(num):
plot[0].remove()
x, y, z = 1.5 * r * np.sin(ph), (2 + r * np.cos(ph)) * np.sin(th), (2 + r * np.cos(ph)) * np.cos(th)
plot[0] = ax.plot_surface(1.5 * r * np.sin(ph),(2 + r*np.cos(ph)) * np.sin(th),(z+2),rstride=2,cstride=1,color='green',alpha=.5)
ax.view_init(azim=360*num/100, elev=10)
ani = animation.FuncAnimation(fig, update, 100,interval=40)
plt.show()
這就是 output 在 30fps 時的樣子:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.