python - 有没有一种简单的方法可以在 matplotlib 中为滚动垂直线设置动画?
问题描述
我想拥有一个在音频播放实用程序中似乎很常见的进度标记。我认为在 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()
解决方案
axvline()
只需返回一个Line2D
对象,因此您可以使用更新其位置Line2D.set_xdata()
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()
请注意,刷新率并不能保证,它取决于重绘图形所需的时间。你可能不得不玩弄refreshPeriod
.
推荐阅读
- gradle - findByName() 方法为 gradle 插件任务返回 null
- linux - Kali Linux 安装 Bluto
- ubuntu-14.04 - inotifywait 偷偷消耗大量内存
- wiremock - 使用我自己的自签名证书连接到 Wiremock 时出现 SSLHandshakeException
- google-bigquery - 如何比较 Google Bigquery 中的先前行和当前行?
- python - 无法杀死 macOS python 进程
- python - 使用 Python Selenium 时缺少数据/内容
- flutter - 应用程序用户之间的区块链 BFT 共识的 Flutter 包
- windows - 在 MRTK 2.3 中启用“空间感知系统”时,HoloLens(第一代)-模拟器上的应用程序崩溃
- c# - 与常规垃圾收集相比,.NET Core 中的 AssemblyLoadContext.Unload() 的值是多少?