Python 有没有一种简单的方法可以在matplotlib中设置滚动垂直线的动画?

Python 有没有一种简单的方法可以在matplotlib中设置滚动垂直线的动画?,python,matplotlib,animation,seaborn,Python,Matplotlib,Animation,Seaborn,我想有什么我会描述为一个进步的标志,似乎很常见的音频播放实用程序。我认为在matplotlib中,这相当于左/右动画plt.vlines。我的代码获取2秒的数据数组,并创建音频时间序列可视化。我正在努力创建一条动画垂直线,从0到2在绘图上线性移动2秒 import seaborn as sns import numpy as np import matplotlib.pyplot as plt font = {'weight': 'bold', 'size': 15} plt.rc('font

我想有什么我会描述为一个进步的标志,似乎很常见的音频播放实用程序。我认为在matplotlib中,这相当于左/右动画
plt.vlines
。我的代码获取2秒的数据数组,并创建音频时间序列可视化。我正在努力创建一条动画垂直线,从0到2在绘图上线性移动2秒

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

font = {'weight': 'bold', 'size': 15}
plt.rc('font',**font)
sns.set_style("darkgrid")

testSeries = np.random.randint(-10, 20, 12000)
testSeries = testSeries - testSeries.mean()


fig,axis = plt.subplots(nrows=1,ncols=1,figsize=(18,5),sharex=True)
sns.lineplot(range(0,len(testSeries)),testSeries,  color='#007294')
plt.xlim(0, len(testSeries))
axis.set_xlabel("Time (s)", fontsize='large', fontweight='bold')
axis.set_ylabel("Amplitude", fontsize='large', fontweight='bold')
axis.set_xticklabels(['0', '0.3', '0.6', '1', '1.3', '1.6', '2'],fontsize=15)
fig.tight_layout(rect=[0,0,.8,1]) 
plt.subplots_adjust(bottom=-0.01)
sns.despine()
plt.show()

matplotlib
的交互模式可能对您有用。以下是如何设置它:

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


testSeries = np.random.randint(-10, 20, 1000)
testSeries = testSeries - testSeries.mean()

x = range(0,len(testSeries))
fig,ax = plt.subplots(nrows=1,ncols=1)

line = ax.plot((x[0], x[0]), (0, testSeries[0]), 'k-',linewidth=4)

plt.xlim(0, len(testSeries))
plt.ion()   # set interactive mode
plt.show()

ax.set_xlabel("Time (s)", fontsize='large', fontweight='bold')
ax.set_ylabel("Amplitude", fontsize='large', fontweight='bold')
ax.set_xticklabels(['0', '0.3', '0.6', '1', '1.3', '1.6', '2'],fontsize=15)

for i,serie in enumerate(testSeries):
#comment the following three lines if you don't want to remove previous lines

    for l in line:
        l.remove()
        del l

    line = ax.plot((x[i], x[i]), (0, testSeries[i]), 'k-',linewidth=4)
    plt.gcf().canvas.draw()
    plt.pause(0.01)
输出(保留前几行):

输出(删除前几行):
axvline()
只返回一个
Line2D
对象,因此您可以使用
Line2D.set\u xdata()更新其位置


请注意,刷新率不是保证的,它取决于重新绘制图形所需的时间。您可能需要使用
refreshPeriod

这不是我想要实现的目标,但它仍然是一个有趣的解决方案。
duration = 2 # in sec
refreshPeriod = 100 # in ms

fig,ax = plt.subplots()
vl = ax.axvline(0, ls='-', color='r', lw=1, zorder=10)
ax.set_xlim(0,duration)

def animate(i,vl,period):
    t = i*period / 1000
    vl.set_xdata([t,t])
    return vl,

ani = animation.FuncAnimation(fig, animate, frames=int(duration/(refreshPeriod/1000)), fargs=(vl,refreshPeriod), interval=refreshPeriod)
plt.show()