我想用在 for 回圈的每次迭代中计算的值更新我的 matplotlibplot。这个想法是我可以实时查看计算了哪些值,并在我的脚本运行时逐次观察进度迭代。我不想首先遍历回圈,存盘值然后执行绘图。
一些示例代码在这里:
from itertools import count
import random
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
def animate(i, x_vals, y_vals):
plt.cla()
plt.plot(x_vals, y_vals)
if __name__ == "__main__":
x_vals = []
y_vals = []
fig = plt.figure()
index = count()
for i in range(10):
print(i)
x_vals.append(next(index))
y_vals.append(random.randint(0, 10))
ani = FuncAnimation(fig, animate, fargs=(x_vals, y_vals))
plt.show()
我在网上看到的大多数示例都处理影片的所有内容都是全域变量的情况,我想避免这种情况。当我使用除错器逐行执行我的代码时,图形确实出现并且它是影片的。当我在没有除错器的情况下运行脚本时,图形显示但没有绘制任何内容,我可以看到我的回圈没有通过第一次迭代,首先等待图形视窗关闭然后继续。
uj5u.com热心网友回复:
在 matplotlib 中制作影片时永远不应该使用回圈。
该animate
函式会根据您的时间间隔自动呼叫。
这样的事情应该作业
def animate(i, x=[], y=[]):
plt.cla()
x.append(i)
y.append(random.randint(0, 10))
plt.plot(x, y)
if __name__ == "__main__":
fig = plt.figure()
ani = FuncAnimation(fig, animate, interval=700)
plt.show()
uj5u.com热心网友回复:
有许多替代方案可能会在不同情况下派上用场。这是我使用过的一种:
import matplotlib.pyplot as plt
import numpy as np
from time import sleep
def main():
x = np.linspace(0, 30, 51)
y = np.linspace(0, 30, 51)
xx, yy = np.meshgrid(x, y)
# plt.style.use("ggplot")
plt.ion()
fig, ax = plt.subplots()
fig.canvas.draw()
for n in range(50):
# compute data for new plot
zz = np.random.randint(low=-10, high=10, size=np.shape(xx))
# erase previous plot
ax.clear()
# create plot
im = ax.imshow(zz, vmin=-10, vmax=10, cmap='RdBu', origin='lower')
# Re-render the figure and give the GUI event loop the chance to update itself
# Instead of the two lines one can use "plt.pause(0.001)" which, however gives a
# decepracted warning.
# See https://github.com/matplotlib/matplotlib/issues/7759/ for an explanation.
fig.canvas.flush_events()
sleep(0.1)
# make sure that the last plot is kept
plt.ioff()
plt.show()
此外,set_data(...)
如果仅资料更改并且您不想重新绘制整个图形(因为这非常耗时),则线图或 imshow 物件的方法很有用。
0 评论