栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何为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()


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640114.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号