我对 matplotlib 完全陌生,经验丰富但对 python 生疏,我目前正在努力使用 matplotlib。 我正在尝试为情节上的一个点设置动画,就像这样: https://www.desmos.com/calculator/rv8gbimhon
我已经为它编写了代码,但是在 while 循环期间绘图不会实时更新该点,相反,while 循环会暂停,直到我关闭绘图窗口并且循环的下一次迭代发生,使用更新的坐标重新打开绘图。有没有办法在不打开和关闭窗口的情况下在 matplotlib 上移动一个点?
我的代码:
func7 <- function(x, y) sqrt(rowSums((y-x[col(y)])^2))
microbenchmark::microbenchmark(func1(x, y), func3(x, y), func4(x, y), func7(x, y))
#Unit: microseconds
# expr min lq mean median uq max neval cld
# func1(x, y) 37.605 39.7475 61.17471 40.7595 42.1865 1955.888 100 a
# func3(x, y) 22.212 23.5945 68.63660 24.8320 25.8670 4333.933 100 a
# func4(x, y) 21.089 22.7930 24.11542 23.5945 24.2315 58.050 100 a
# func7(x, y) 7.731 8.9135 44.45935 10.0615 10.9500 3415.959 100 a
答案 0 :(得分:0)
循环更新绘图的一个选项是打开 interactive mode 并使用 pause 更新绘图。
例如:
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)
但是,对于更高级的动画,我建议使用 animation class。