python matplotlib 从函数更新散点图

标签 python matplotlib scatter-plot

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

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

我得到的(在整个运行结束时)是这样的: 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()(“交互式”)。然后需要先绘制图形,然后循环更新绘图。在循环内部,我们需要绘制 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/

相关文章:

r - 为什么我的线性回归拟合线看起来不对?

r - 如何在 R 中的散点图上生成特定数量的 Y 轴刻度线

python - 如何在python27中的数据框中查找行中的公共(public)元素

python - 从字典列表中删除某些键

python - 如何在mac上的python虚拟环境中安装 basemap ?

python - 如何在 Matplotlib 中编写分段函数 latex 代码?

c# - 如何创建 3D 散点图?

python - 用年份绘制 pandas 数据框

python - 如何根据元组内容拆分 numpy 数组?

python - 带有第二个 y 轴的 Seaborn 图