如何为Matplotlib中的颜色栏设置动画

如何为Matplotlib中的颜色栏设置动画,第1张

如何为Matplotlib中的颜色栏设置动画

虽然我不确定如何使用来具体实现

ArtistAnimation
,但使用还是
FuncAnimation
很简单的。如果我对您的“原始”版本1进行了以下修改,则可以正常工作。

修改版本1

import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom mpl_toolkits.axes_grid1 import make_axes_locatablefig = plt.figure()ax = fig.add_subplot(111)# I like to position my colorbars this way, but you don't have todiv = make_axes_locatable(ax)cax = div.append_axes('right', '5%', '5%')def f(x, y):    return np.exp(x) + np.sin(y)x = np.linspace(0, 1, 120)y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)frames = []for i in range(10):    x       += 1    curVals  = f(x, y)    frames.append(curVals)cv0 = frames[0]cf = ax.contourf(cv0, 200)cb = fig.colorbar(cf, cax=cax)tx = ax.set_title('frame 0')def animate(i):    arr = frames[i]    vmax     = np.max(arr)    vmin     = np.min(arr)    levels   = np.linspace(vmin, vmax, 200, endpoint = True)    cf = ax.contourf(arr, vmax=vmax, vmin=vmin, levels=levels)    cax.cla()    fig.colorbar(cf, cax=cax)    tx.set_text('frame {0}'.format(i))ani = animation.FuncAnimation(fig, animate, frames=10)plt.show()

主要区别在于,我在函数中执行关卡计算和轮廓绘制,而不是创建艺术家列表。由于您可以清除上一帧中的轴并在每帧中重做轴,因此色条起作用。

使用

contour
或时
contourf
,必须重做,因为您不能只是动态地更改数据。但是,当您绘制了许多轮廓线并且结果看起来很平滑时,我认为最好
imshow
改用它-
这意味着您实际上可以只使用同一位艺术家并更改数据,并且颜色栏会自动更新。它也快得多!

更好的版本

import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom mpl_toolkits.axes_grid1 import make_axes_locatablefig = plt.figure()ax = fig.add_subplot(111)# I like to position my colorbars this way, but you don't have todiv = make_axes_locatable(ax)cax = div.append_axes('right', '5%', '5%')def f(x, y):    return np.exp(x) + np.sin(y)x = np.linspace(0, 1, 120)y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)# This is now a list of arrays rather than a list of artistsframes = []for i in range(10):    x       += 1    curVals  = f(x, y)    frames.append(curVals)cv0 = frames[0]im = ax.imshow(cv0, origin='lower') # Here make an AxesImage rather than contourcb = fig.colorbar(im, cax=cax)tx = ax.set_title('frame 0')def animate(i):    arr = frames[i]    vmax     = np.max(arr)    vmin     = np.min(arr)    im.set_data(arr)    im.set_clim(vmin, vmax)    tx.set_text('frame {0}'.format(i))    # In this version you don't have to do anything to the colorbar,    # it updates itself when the mappable it watches (im) changesani = animation.FuncAnimation(fig, animate, frames=10)plt.show()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5645921.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存