python matplotlib从函数更新散点图

2024-06-06 18:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我只在整个过程结束时绘制了所有数据,而我一直在尝试将数据添加并绘制到画布中。

我得到的(在整个跑步结束时)是: enter image description here

然而,我追求的是: enter image description here

我的代码的简化版本:

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()

Tags: 数据run代码in时间来源绘制plt
2条回答

有几种方法可以设置matplotlib绘图的动画。下面让我们看两个使用散点图的最小示例。

(a) 使用交互模式plt.ion()

要制作动画,我们需要一个事件循环。获取事件循环的一种方法是使用plt.ion()(“interactive on”)。然后需要先绘制图形,然后在循环中更新绘图。在循环中,我们需要绘制画布,并为窗口处理其他事件(如鼠标交互等)引入一点暂停。没有这个停顿,窗户就会结冰。最后,我们调用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

上面的大部分可以使用^{}自动完成。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()

据我所知,你想互动地更新你的情节。如果是这样,您可以使用plot而不是scatterplot,并像这样更新plot的数据。

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管理或使用的任何通信过程)。 我希望有帮助。

相关问题 更多 >