如何在 matplotlib 中为轮廓标签设置动画?

时间:2021-05-03 00:31:23

标签: python matplotlib animation contour

我使用 this question 作为框架来创建大气压力等高线动画。我在下面粘贴了我用作指南的答案代码。这个答案没有标记轮廓。我的问题是,如何使用以下内容为轮廓标签设置动画:

ax.clabel(p[0], inline=1, fontsize=10)

我喜欢下面的模型,因为它没有将 ax 清除为函数的一部分。我知道我可以清除 ax 作为动画功能的一部分并重新绘制和重新标记轮廓,但我不想这样做,因为在我的项目中我有其他绘图,我只是在其中更新数据函数,因此无法清除 ax。我想我需要删除旧标签并添加新标签,但我不知道该怎么做。

额外问题:据我所知,轮廓是唯一一种不能简单地在动画函数中重置数据的绘图类型。这是为什么?

以下是我用作模板的代码:

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

x= np.linspace(0,3*np.pi)
X,Y = np.meshgrid(x,x)
f = lambda x,y, alpha, beta :(np.sin(X+alpha)+np.sin(Y*(1+np.sin(beta)*.4)+alpha))**2
alpha=np.linspace(0, 2*np.pi, num=34)
levels= 10
cmap=plt.cm.magma


fig, ax=plt.subplots()
props = dict(boxstyle='round', facecolor='wheat')
timelabel = ax.text(0.9,0.9, "", transform=ax.transAxes, ha="right", bbox=props)
t = np.ones(10)*time.time()
p = [ax.contour(X,Y,f(X,Y,0,0), levels, cmap=cmap ) ]

def update(i):
    for tp in p[0].collections:
        tp.remove()
    p[0] = ax.contour(X,Y,f(X,Y,alpha[i],alpha[i]), levels, cmap= cmap) 
    t[1:] = t[0:-1]
    t[0] = time.time()
    timelabel.set_text("{:.3f} fps".format(-1./np.diff(t).mean()))  
    return p[0].collections+[timelabel]

ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(alpha), 
                                         interval=10, blit=True, repeat=True)
plt.show()

0 个答案:

没有答案