编程语言
首页 > 编程语言> > python matplotlib更新函数的散点图

python matplotlib更新函数的散点图

作者:互联网

我正在尝试自动更新散点图.
我的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()

解决方法:

有几种方法可以对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()

标签:scatter-plot,python,matplotlib
来源: https://codeday.me/bug/20190915/1806465.html