Python:matplotlib - 循环、清除并在同一图形上显示不同的图

标签 python matlab matplotlib plot

我想使用循环查看绘图如何随不同的值而变化。我想在同一个情节上看到它。但我不想保留图中先前的情节。在 MATLAB 中,这可以通过创建图形并在同一图形上绘图来实现。循环结束时关闭它。

喜欢,

fh = figure();
%for loop here
%do something with x and y    
subplot(211), plot(x);
subplot(212), plot(y); 
pause(1)
%loop done
close(fh);

我无法在 matplotlib 中找到与此等效的内容。通常所有的问题都与在同一个图上绘制不同的系列有关,这在 matplotlib 上似乎很自然,通过使用 plt.plot() 绘制几个系列,然后最终使用 显示它们plt.show()。但是我想刷新剧情。

最佳答案

在 matplotlib 中创建动画基本上有两种不同的方法

交互模式

使用 plt.ion() 可以打开更多交互。即使尚未调用 show,这也会创建一个绘图。可以通过调用 plt.draw() 或为动画调用 plt.pause() 来更新绘图。

import matplotlib.pyplot as plt

x = [1,1]
y = [1,2]

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, sharey=True)
line1, = ax1.plot(x)
line2, = ax2.plot(y)
ax1.set_xlim(-1,17)
ax1.set_ylim(-400,3000)
plt.ion()

for i in range(15):
    x.append(x[-1]+x[-2])
    line1.set_data(range(len(x)), x)
    y.append(y[-1]+y[-2])
    line2.set_data(range(len(y)), y)

    plt.pause(0.1)

plt.ioff()    
plt.show()

函数动画

Matplotlib 提供了一个 animation submodule ,这简化了创建动画的过程,还可以轻松保存它们。与上面相同,使用 FuncAnimation 看起来像:

import matplotlib.pyplot as plt
import matplotlib.animation

x = [1,1]
y = [1,2]

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, sharey=True)
line1, = ax1.plot(x)
line2, = ax2.plot(y)
ax1.set_xlim(-1,18)
ax1.set_ylim(-400,3000)


def update(i):
    x.append(x[-1]+x[-2])
    line1.set_data(range(len(x)), x)
    y.append(y[-1]+y[-2])
    line2.set_data(range(len(y)), y)

ani = matplotlib.animation.FuncAnimation(fig, update, frames=14, repeat=False)   
plt.show()

下面是一个改变频率及其功率谱的正弦波动画示例:

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

x = np.linspace(0,24*np.pi,512)
y = np.sin(x)

def fft(x):
    fft = np.abs(np.fft.rfft(x))
    return fft**2/(fft**2).max()

fig, (ax1,ax2) = plt.subplots(nrows=2)
line1, = ax1.plot(x,y)
line2, = ax2.plot(fft(y))
ax2.set_xlim(0,50)
ax2.set_ylim(0,1)

def update(i):
    y = np.sin((i+1)/30.*x)
    line1.set_data(x,y)
    y2 = fft(y)
    line2.set_data(range(len(y2)), y2)

ani = matplotlib.animation.FuncAnimation(fig, update, frames=60, repeat=True)  
plt.show()

enter image description here

关于Python:matplotlib - 循环、清除并在同一图形上显示不同的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157538/

相关文章:

Python 使用 Matplotlib 将总计添加到绘图中

python - 在Python中检查值是否存在于一系列开始和结束位置中的最有效方法是什么?

Python 将 "March 2 2012"转换为日期时间对象

matlab - bwmorph 分支点如何工作?

algorithm - 如何有效地对分区数组进行排序?

python - 如何在颜色条顶部强制使用指数的科学记数法

python - PySide 代替 PyQt4 作为 matplotlib Qt4Agg 后端的先决条件

python - iOS+GoogleChrome 上的“内容处置”[Google App Engine 上的 Flask]

python - 在ubuntu python django服务中安装reportLab

matlab - Matlab 中的 eval() 命令