繁体   English   中英

python matplotlib从函数更新散点图

[英]python matplotlib update scatter plot from a function

我正在尝试自动更新散点图。 我的X和Y值的来源是外部的,并且数据在非预期的时间间隔(轮数)中自动推送到我的代码中。

我只设法在整个过程结束时绘制所有数据,而我试图不断地将数据添加并绘制到画布中。

我得到的(在整个运行结束时)是这样的: 在此处输入图片说明

而我所追求的是: 在此处输入图片说明

我的代码的简化版本:

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() (“交互式打开”)。 然后需要先绘制图形,然后可以循环更新图形。 在循环内部,我们需要绘制画布并为窗口添加一些暂停以处理其他事件(例如鼠标交互等)。 没有此暂停,窗口将冻结。 最后,我们调用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()

据我了解,您想以交互方式更新绘图。 如果是这样,您可以使用图代替散点图,并像这样更新图的数据。

import numpy
import matplotlib.pyplot as plt 
fig = plt.figure()
axe = fig.add_subplot(111)
X,Y = [],[]
sp, = axe.plot([],[],label='toto',ms=10,color='k',marker='o',ls='')
fig.show()
for iter in range(5):
    X.append(numpy.random.rand())
    Y.append(numpy.random.rand())
    sp.set_data(X,Y)
    axe.set_xlim(min(X),max(X))
    axe.set_ylim(min(Y),max(Y))
    raw_input('...')
    fig.canvas.draw()

如果这是您要寻找的行为,则只需创建一个附加sp数据的函数,然后在该函数中获取要绘制的新点(通过I / O管理或您正在执行的任何通信过程)使用)。 希望对您有所帮助。

暂无
暂无

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

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