【发布时间】:2022-01-24 09:15:07
【问题描述】:
尝试绘制两个单独的动画,即在不同的窗口中作为单独的图形。为我运行此代码正确地创建了两个窗口,但同时为第二个图形上的数据设置动画。关闭图 1 会导致仅对图 2 的预期数据进行动画处理,从用于图 1 的数据中删除重叠。关闭图 2 会导致仅对图 1 的预期数据进行动画处理,从用于图的数据中删除重叠2.
以下最少代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
dx, dv, N, Nb, decp = 2, 1.5, 100, 12, int(1)
Pd = np.zeros([N + 1, 2 * Nb])
Vd = np.zeros([N + 1, 2 * Nb])
Pd[:, 1] = 4
Vd[:, 3] = 2
t = np.zeros(N + 1)
t[0] = 0
for i in range(0, N):
t[i + 1] = (i + 1) * 0.1
Px = []
for i in range(0, (2 * Nb)):
PX = dx * (-Nb + i) / 4
Px.append(PX)
lblx = []
for i in range(0, int((Nb / 2) + 1)):
if i == (Nb / 4):
LBL = r"$\mu_x$"
lblx.append(LBL)
else:
LBL = r"${0}\sigma_x$".format(-(Nb / 4) + i)
lblx.append(LBL)
Pv = []
for i in range(0, (2 * Nb)):
PV = dv * (-Nb + i) / 4
Pv.append(PV)
lblv = []
for i in range(0, int((Nb / 2) + 1)):
if i == (Nb / 4):
LBL = r"$\mu_v$"
lblv.append(LBL)
else:
LBL = r"${0}\sigma_v$".format(-(Nb / 4) + i)
lblv.append(LBL)
fig1 = plt.figure(figsize=(8,6))
def animatex(i):
fig1.clear()
plt.bar(Px, Pd[i, :], width = dx / 4, align = 'edge', color = 'b', \
label = 't = {} seconds'.format(round(t[i], decp)))
s_ticks = np.arange(-3 * dx, (3 + 1) * dx, dx)
plt.xticks(s_ticks, lblx)
plt.ylim(0, np.max(Pd))
plt.xlim(-3 * dx, 3 * dx)
plt.legend()
plt.draw()
anix = FuncAnimation(fig1, animatex, repeat = True, interval = 200, frames = N + 1)
fig2 = plt.figure(figsize=(8,6))
def animatev(i):
fig2.clear()
plt.bar(Pv, Vd[i, :], width = dv / 4, align = 'edge', color = 'b', \
label = 't = {} seconds'.format(round(t[i], decp)))
s_ticks = np.arange(-3 * dv, (3 + 1) * dv, dv)
plt.xticks(s_ticks, lblv)
plt.ylim(0, np.max(Vd))
plt.xlim(-3 * dv, 3 * dv)
plt.legend()
plt.draw()
aniv = FuncAnimation(fig2, animatev, repeat = True, interval = 200, frames = N + 1)
plt.show()
可能很清楚,它们是两个条形图,具有不同的垂直和水平尺寸。我已经看到了针对此类问题的一些解决方案,其中数据通过共享变量共享轴,但在这里它们不是(可以看出)。 对于这个最小代码,解决方案包括让两个条形图,一个在 Pd 中,另一个在 Vd 中,位于它们各自的预期数字上,而不是同时在第二个数字上。
如果此处的信息有任何问题,例如未满足最低代码要求、更多信息等,请告诉我,我会更新。
忽略任何任性的写作风格,这无关紧要。
【问题讨论】:
-
不要使用
plt。而是制作一个轴并使用轴上的方法:fig2, ax2 = plt.subplots(); fig2.clear(); ax2.bar(...) etc -
@JodyKlymak 只需将所有 plt 替换为 axi, i=[1,2] 并将 figi = plt.figure(figsize=(8,6)) 更改为 figi, axi = plt.subplots()。然后 FuncAnimation 给出以下错误:“TypeError:draw_wrapper() 缺少 1 个必需的位置参数:'renderer'”。只是将“axi”作为参数放在 FuncAnimation 中并不能解决这个问题。如果我在您的解决方案中没有看到简单性,请道歉。
标签: python matplotlib