python - 使用 matplotlib 绘制动态数据

标签 python numpy matplotlib plot scipy

我正在编写一个应用程序来显示动态变化的数据(从套接字读取的数据)。

作为一个虚拟案例,我尝试绘制一个振幅每秒乘以 1.1 的正弦波:

import numpy as np
import matplotlib.pyplot as plt
import time

x = np.arange(0, 10, 0.1);
y = np.sin(x)


for i in xrange(100):
    plt.plot(x, y)
    time.sleep(1)
    y=y*1.1

这显然不是这样做的方式,但它表明了我的意图。

如何正确完成?

编辑: 以下是@mskimm 回答中建议的代码的回溯输出:

plt.show() #Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 505, in run
    self.__target(*self.__args, **self.__kwargs)
  File "<ipython-input-5-ed773f8e3e84>", line 7, in update
    plt.draw()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 466, in draw
    get_current_fig_manager().canvas.draw()
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 240, in draw
    tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/tkagg.py", line 12, in blit
    tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
RuntimeError: main thread is not in main loop

编辑 2:

事实证明,相同的代码在 qtconsole 中运行时可以正常工作...(知道为什么吗?) 然而,每张打印品都会重新缩放以绘制情节,因此缺少“动画效果”。 我尝试使用 plt.autoscale_view(False,False,False) 但这根本没有引起任何情节。

最佳答案

使用 matplotlib animation API 有更好的方法来做到这一点, 但这里有一个快速而肮脏的方法:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 10, 0.1)
y = np.sin(x)

plt.ion()
ax = plt.gca()
ax.set_autoscale_on(True)
line, = ax.plot(x, y)

for i in xrange(100):
    line.set_ydata(y)
    ax.relim()
    ax.autoscale_view(True,True,True)
    plt.draw()
    y=y*1.1
    plt.pause(0.1)

关键步骤是:

  1. 使用 plt.ion() 打开交互模式。
  2. 跟踪您要更新的行,并覆盖它们的数据,而不是再次调用 plot
  3. 通过调用 plt.pause 给 Python 一些时间来更新绘图窗口。

我包含了自动缩放视口(viewport)的代码,但这并不是绝对必要的。

关于python - 使用 matplotlib 绘制动态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23058560/

相关文章:

python - python Argparse 中的额外字符?

python - Matplotlib 可拖动数据标记

python - 减去 Pandas 列中的时间

python - LinearSVC中 `penalty`和 `loss`的含义

python - 在没有双循环的情况下展平 numpy 数组

python - 如何使用 pandas DataFrame 的值作为 numpy 数组索引

python - 来自事件坐标的 Matplotlib 日期时间

python matplotlib "merge"用于多索引的x轴标签

python - 自动初始化实例变量?

python - pandas 和 numpy 的交互