Python Matplotlib 函数动画

标签 python animation matplotlib

您好,亲爱的 StackOverfloooow 成员(member), 我无法理解 matplotlib 的 FuncAnimation 模块。你介意帮我一下吗?我有两个问题:

  1. 为什么 die initanimate 函数在仅返回 PLOT 之后都需要一个逗号?
  2. 为什么我的代码不更新 time_text?如果我让它在每个动画之后打印 t,我会在控制台中正确地添加一个,但文本不会在绘图中更新。

.

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

fig = plt.figure()
sub = fig.add_subplot(111,xlim=(0, 10), ylim=(0, 1))
PLOT, = sub.plot([],[])
time_text = sub.text(1,1,"",transform = sub.transAxes, ha="right")
t = 0

def init():
    PLOT.set_data([],[])
    time_text.set_text("")
    return PLOT,time_text

def animate(i):
    global t
    x = np.linspace(0,10,1000)
    y = np.exp(- ((x-0.01*i)/(2))**2 )/np.sqrt(2*np.pi)
    t += 1

    PLOT.set_data(x,y)
    time_text.set_text("time = "+str(t))
    return PLOT, time_text

ani = animation.FuncAnimation(fig, animate, init_func=init, frames=2000, interval=20, blit=True)

plt.show()

最佳答案

1) 不太确定你的意思。在 initanimate 中,你需要同时返回 PLOTtime_text,所以你用逗号分隔它们每个函数都会返回一个元组。

对于 PLOT, = sub.plot([],[]) 中的“悬挂”逗号,sub.plot 返回一个包含单个元素的列表,一个 matplotlib.lines.Line2D 对象。 PLOT, 正在解压缩这个单个元素列表。所以,你也可以这样做:

PLOT = sub.plot([],[])[0]

获取元素。

2) 您的代码确实更新了 time_text,您只是将其绘制在图形的边界之外。例如更改:

time_text = sub.text(1,1,"",transform = sub.transAxes, ha="right")

收件人:

time_text = sub.text(1,0,"",transform = sub.transAxes, ha="right")

让它显示在右下角,或者 0.5, 0.5 让它显示在屏幕中间。

关于Python Matplotlib 函数动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083439/

相关文章:

javascript - 创建圆形鼠标悬停饱和效果

javascript - 如何在 jquery 动画函数中传递原始显示属性?

python - Pandas matplotlib.pyplot 按列值添加图例

python成员变量列表不是最新的

python - 类型错误 : 'module' object is not callable in Playsound module

ios - 向上移动 subview 时如何使用现有的约束自动布局?

python - 将多条线绘制到单个 Python 图形上

python - 我在 matplotlib (python) 中有一个带有误差线的条形图,但我想要误差线在中间。我该怎么做呢?谢谢

python - ctypes - 查看返回结构的 c_char_p 字段

python - 如何在 TensorFlow 中索引稀疏张量?