下面的分隔部分(注释之间的部分)是否可以封装在函数中?
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
def f(t):
x=np.random.rand(1)
y=np.random.rand(1)
return x,y
# From here
fig, ax = plt.subplots()
ax.set_xlim(0,1)
ax.set_ylim(0,1)
# To here
def update(t):
x,y = f(t)
ax.plot(x, y, marker="s")
ax.set_title(str(t))
ani = matplotlib.animation.FuncAnimation(fig, update, frames=100)
plt.show()
谢谢
答案 0 :(得分:2)
不确定问题是什么。但答案当然是肯定的,任何东西都可以放入函数中。
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
def f(t):
x=np.random.rand(1)
y=np.random.rand(1)
return x,y
def function():
fig, ax = plt.subplots()
ax.set_xlim(0,1)
ax.set_ylim(0,1)
return fig,ax
def update(t):
x,y = f(t)
ax.plot(x, y, marker="s")
ax.set_title(str(t))
fig, ax = function()
ani = matplotlib.animation.FuncAnimation(fig, update, frames=100)
plt.show()