更新 matplotlib 动画 3D 中的 x/y/z 限制

问题描述 投票:0回答:1

当我尝试调整 3D 动画中轴的限制时,我遇到了这个问题。屏幕上的限制范围似乎不是我想要的,但控制台上的限制输出是好的。绘图线无法在坐标区中很好地显示。我很困惑,因为我不知道问题出在哪里。谁能帮我?非常感谢!

这是我的代码。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button, TextBox
from matplotlib import animation
x = np.array([0.0])
y = np.array([1.0])
z = np.array([0.0])
v = np.array([1.0, 0.0, 1.0])
tmax = 1
tmin = 0
fig2 = plt.figure()
# fig2.set_visible(False)
ax = fig2.add_axes([0.075, 0.1, 0.6, 0.8],projection='3d')


def set_axes_equal(ax: plt.Axes):

    limits = np.array([ax.get_xlim3d(),ax.get_ylim3d(),ax.get_zlim3d(),])
    origin = np.mean(limits, axis=1)
    radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))
    _set_axes_radius(ax, origin, radius)

def _set_axes_radius(ax, origin, radius):
    x, y, z = origin
    ax.set_xlim3d([x - radius, x + radius])
    ax.set_ylim3d([y - radius, y + radius])
    ax.set_zlim3d([z - radius, z + radius])

ax.set_box_aspect((1, 1, 1))

def set_lim():
    global tmax, tmin

    tmax = max(np.max(x), np.max(y), np.max(z))

    tmin = min(np.min(x), np.min(y), np.min(z))
    print(ax.get_xlim3d())

    if tmax != tmin:
        ax.set_xlim(tmin, tmax)
        ax.set_ylim(tmin, tmax)
        ax.set_zlim(tmin, tmax)
    else: 
        ax.set_xlim(-10, 10)
        ax.set_ylim(-10, 10)
        ax.set_zlim(-10, 10)

k = 1.0
dt = 0.1

p, = ax.plot(x, y, z)

def fv(v:np.ndarray):
    return np.cross(v, np.array([0., 0., 1.]))

def runge_kutta(y:np.ndarray, t:float, f):
    k1 = t * f(y)
    k2 = t * f(y + 0.5 * k1)
    k3 = t * f(y + 0.5 * k2)
    k4 = t * f(y + k3)
    return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6.

def update(i):
    global k, dt, p, x, y, z, v
    v = runge_kutta(v, dt, fv)
    dx = x[-1] + v[0] * dt
    dy = y[-1] + v[1] * dt
    dz = z[-1] + v[2] * dt
    x = np.append(x, [dx])
    y = np.append(y, [dy])
    z = np.append(z, [dz])
    set_lim()
    set_axes_equal(ax)
    if i >= 50:x, y, z = x[1:], y[1:], z[1:]
    p.set_data_3d(x, y, z)
    return (p,)
   

ani = animation.FuncAnimation(fig2, update, interval=100, frames=None, blit=True)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

当程序自行运行时:look, the plot line is out of the range

当我移动相机时:now the limits are correct

请原谅我糟糕的英语。我一直试图尽可能清楚地表达我的问题。如果对以上内容有任何疑问,我会尽力解释。

手动调整相机位置可以使限制更新成功,但无法自行更新。我只是希望情节线可以位于 Axes3D 的中心,而无需手动调整相机位置。希望有人能帮助我...

python matplotlib animation matplotlib-animation matplotlib-3d
1个回答
0
投票

当您告诉

matplotlib.animation.FuncAnimation
blit
时,它似乎会停止更新轴。将您的线路替换为这一行:

ani = animation.FuncAnimation(fig2, update, interval=100, frames=None)

它应该像你描述的那样工作。

如果您有任何疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.