想要设置两个散布和一个绘图的动画,但不发生

2024-05-23 15:09:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在给x和y添加一些小值,但是我不太了解,所以请帮我解决这个问题。 我所关心的基本问题是如何移动1号图角上的2个散点

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

fig, ax = plt.subplots()

xori = 0.007
xdest = 0.5
yori = 0.97
ydest = 0.5

line, = ax.plot([0.007, 0.97], [0.5, 0.5], c='C2', zorder=1, alpha=0.2, linewidth=1)
dotOne = ax.scatter(0.007, 0.5, s=80, c='C2', zorder=2)
dotTwo = ax.scatter(0.97, 0.5,  s=80, c='C2', zorder=2)


def animate(xori, xdest, yori, ydest):
    print("called")
    xori = xori + 0.001
    xdest = xdest - 0.01
    yori = yori + 0.001
    ydest = ydest - 0.01
    line.set_xdata([xori, xdest])
    line.set_ydata([yori, ydest])
    dotOne.set_offsets([xori,yori])
    dotTwo.set_offsets([xdest,ydest])    
    return line, dotOne, dotTwo

#anim = animate(xori, xdest, yori, ydest)
ani = animation.FuncAnimation(fig, animate(xori, xdest, yori, ydest), interval=1000, blit=True)
plt.show()

Tags: importaslinepltaxc2setanimation
1条回答
网友
1楼 · 发布于 2024-05-23 15:09:54

您需要传递function,而不是函数的结果。可以使用全局变量更改函数内的值

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

xori = 0.007
xdest = 0.5
yori = 0.97
ydest = 0.5

line, = ax.plot([0.007, 0.97], [0.5, 0.5], c='C2', zorder=1, alpha=0.2, linewidth=1)
dotOne = ax.scatter(0.007, 0.5, s=80, c='C2', zorder=2)
dotTwo = ax.scatter(0.97, 0.5,  s=80, c='C2', zorder=2)
ax.set(xlim=(-1,1), ylim=(-3,3))

def animate(i):
    global xori, xdest, yori, ydest
    xori = xori + 0.001
    xdest = xdest - 0.01
    yori = yori + 0.001
    ydest = ydest - 0.01
    line.set_xdata([xori, xdest])
    line.set_ydata([yori, ydest])
    dotOne.set_offsets([xori,yori])
    dotTwo.set_offsets([xdest,ydest])    
    return line, dotOne, dotTwo

ani = animation.FuncAnimation(fig, animate, interval=100, blit=True)
plt.show()

相关问题 更多 >