我正在尝试自动更新散点图。 我的 X 和 Y 值的来源是外部的,并且数据会在非预测的时间间隔(轮次)内自动推送到我的代码中。
我只是在整个过程结束时才设法绘制出所有数据,而我正试图不断地将数据添加并绘制到我的 Canvas 中。
我的代码的简化版本:
import matplotlib.pyplot as plt
def read_data():
#This function gets the values of xAxis and yAxis
xAxis = [some values] #these valuers change in each run
yAxis = [other values] #these valuers change in each run
plt.scatter(xAxis,yAxis, label = 'myPlot', color = 'k', s=50)
plt.xlabel('x')
plt.ylabel('y')
plt.show()
最佳答案
有几种方法可以为 matplotlib 绘图制作动画。下面让我们看一下使用散点图的两个最小示例。
(a) 使用交互模式plt.ion()
为了让动画发生,我们需要一个事件循环。获取事件循环的一种方法是使用 plt.ion()
(“交互式”)。然后需要先绘制图形,然后循环更新绘图。在循环内部,我们需要绘制 Canvas 并为窗口引入一点暂停以处理其他事件(如鼠标交互等)。如果没有这个暂停,窗口就会卡住。最后我们调用 plt.waitforbuttonpress()
让窗口在动画结束后保持打开状态。
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
plt.draw()
for i in range(1000):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
fig.canvas.draw_idle()
plt.pause(0.1)
plt.waitforbuttonpress()
(b) 使用FuncAnimation
以上大部分可以使用 matplotlib.animation.FuncAnimation
自动化. FuncAnimation 将负责循环和重绘,并在给定时间间隔后不断调用函数(在本例中为 animate()
)。动画只会在 plt.show()
被调用后开始,从而自动在绘图窗口的事件循环中运行。
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)
def animate(i):
x.append(np.random.rand(1)*10)
y.append(np.random.rand(1)*10)
sc.set_offsets(np.c_[x,y])
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=2, interval=100, repeat=True)
plt.show()
关于python matplotlib 从函数更新散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42722691/