简体   繁体   English

有没有办法在不关闭 window 的情况下更新 matplotlib plot?

[英]Is there a way to update the matplotlib plot without closing the window?

I'm completely new to matplotlib and decently experienced but rusty with python and I'm struggling to work with matplotlib currently.我对 matplotlib 完全陌生,并且经验丰富但对 python 生锈,我目前正在努力与 matplotlib 合作。 I'm trying to kind of animate a point on the plot, kind of like this: https://www.desmos.com/calculator/rv8gbimhon我正在尝试为 plot 上的一个点设置动画,有点像这样: https://www.desmos.com/calculator/rv8gbimhon

I've written the code for it but the plot doesn't update the point in real time during the while loop, instead, the while loop is paused until I close the plot window and the next iteration of the loop happens, re-opening the plot with the updated coords.我已经为它编写了代码,但是 plot 在 while 循环期间不会实时更新点,而是暂停 while 循环,直到我关闭 plot Z05B8C74CBD96FBF2DE4C1A352702 并重新打开循环的下一个循环带有更新坐标的 plot。 Is there a way to move a point on matplotlib without opening and closing windows?有没有办法在 matplotlib 上移动一个点而不打开和关闭 windows?

My code:我的代码:

import numpy as np
import time
t = 0
start_time = time.time()
while t < 30:
    end_time = time.time()
    t = end_time - start_time
    print(t)
    plt.plot(t,t,"g^")
    plt.show()

One option to update the plot in a loop is to turn on interactive mode and to update the plot using pause .在循环中更新 plot 的一种选择是打开交互模式并使用pause更新 plot 。

For example:例如:

import numpy as np
import matplotlib.pyplot as plt
point = plt.plot(0, 0, "g^")[0]
plt.ylim(0, 5)
plt.xlim(0, 5)
plt.ion()
plt.show()

start_time = time.time()
t = 0
while t < 4:
    end_time = time.time()
    t = end_time - start_time
    print(t)
    point.set_data(t, t)
    plt.pause(1e-10)

However, for more advanced animation I would propose to use the animation class .但是,对于更高级的 animation 我建议使用animation class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM