我想用在 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 物件的方法很有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389339.html
