【问题标题】:Dynamic plot in pythonpython中的动态绘图
【发布时间】:2017-07-22 21:30:35
【问题描述】:

我正在尝试在 Python 中创建一个绘图,其中正在绘制的数据会随着我的模拟进行而更新。在 MATLAB 中,我可以使用以下代码来做到这一点:

t = linspace(0, 1, 100);
figure
for i = 1:100
x = cos(2*pi*i*t);
plot(x)
drawnow
end

我正在尝试在animation 模块中使用matplotlibFuncAnimation 函数在类中执行此操作。它调用了一个函数plot_voltage,它在我的模拟中的每个时间步之后重新计算电压。我的设置如下:

import matplotlib.pyplot as plt
import matplotlib.animation as animation

def __init__(self):
    ani = animation.FuncAnimation(plt.figure(2), self.plot_voltage)
    plt.draw()

def plot_voltage(self, *args):
    voltages = np.zeros(100)
    voltages[:] = np.nan

    # some code to calculate voltage

    ax1 = plt.figure(2).gca()
    ax1.clear()
    ax1.plot(np.arange(0, len(voltages), 1), voltages, 'ko-')`

当我的模拟运行时,数字会显示,但只是冻结。但是,代码运行没有错误。有人可以告诉我我缺少什么吗?

【问题讨论】:

  • 我会把第三个版本改成this answer
  • 谢谢,@cphlewis。该解决方案的问题在于,如果我有另一个函数,比如 count(),它只是对正整数进行计数,并且我在 plt.show() 之后运行它,count() 在关闭绘图之前不会运行。用plt.draw() 替换plt.show() 会导致绘图根本不显示,但随后count() 运行。如何在程序继续运行和count() 运行时更新情节?我的后端是开启交互模式的 Qt5Agg。
  • 在第三种解决方案中,update() 将同时调用您的count(),因此绘图继续。
  • 谢谢,@cphlewis。当我在update() 中包含count() 函数时,代码运行并显示了绘图,但窗口只是冻结并且没有显示任何内容。我的代码是here
  • 永远不要在需要用户交互的程序中使用while True

标签: animation matplotlib


【解决方案1】:

这是使用FuncAnimation将matlab代码翻译成matplotlib:

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

t = np.linspace(0, 1, 100)
fig = plt.figure()
line, = plt.plot([],[])

def update(i):
    x = np.cos(2*np.pi*i*t)
    line.set_data(t,x)

ani = animation.FuncAnimation(fig, update, 
                frames=np.linspace(1,100,100), interval=100)
plt.xlim(0,1)
plt.ylim(-1,1)
plt.show()

【讨论】:

  • 谢谢,但是您上面的评论是正确的-我应该更清楚。我有一个模拟,其中正在更新对象的参数。每次执行更新时,我都想绘制它们的值。 Here 是一个最小的例子。我不一定需要使用animation 包。这只是我正在尝试的事情。当我运行这个示例时,图形没有呈现,窗口也没有响应。当我 ctrl+c 终端时,数字绘图但程序停止。对最好的方法有什么想法吗?
  • 我在下面评论the code at GiHubGist
猜你喜欢
  • 2021-06-29
  • 1970-01-01
  • 2021-04-08
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
相关资源
最近更新 更多