![](/img/trans.png)
[英]How to use 'xdata' in imshow() from MatLab in Python3 imshow()
[英]Updating legend entry using imshow in Python3
我正在尝试添加图例以覆盖显示随机数动画数组的imshow()图。 我希望图例更新以显示我们正在查看的步骤。
我尝试按照此处的步骤操作,该步骤显示了如何使用FuncAnimation为subplots()创建动画图例。 我相信显示动画数组的唯一方法是使用ArtistAnimation()和imshow(),但是这两者中的一个或两者都使我无法遵循链接的解决方案。
我已在工作代码下方附加了生成动画随机数组的信息,图例解决方案(来自链接)已被双注释掉。
任何帮助或建议的补救措施将不胜感激。
谢谢,C
import matplotlib.animation as animation
from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np
N=20
steps = 100
interval_pause = 100
repeat_pause = 1000
cmap = colors.ListedColormap(['white', 'black'])
bounds=[-1,0,1]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig = plt.figure()
ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
ax.axes.xaxis.set_ticks([])
ax.axes.yaxis.set_ticks([])
#plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[-1,0,1])
array = 2*(np.random.rand(N,N,steps)-0.5)
state = np.zeros(steps)
ims = []
##leg = ax.legend(loc='upper left',prop={'size':12})
for step in range(0,steps):
state = array[:,:,step]
im = plt.imshow(state,interpolation='nearest',cmap=cmap,norm=norm, animated=True)
##lab = 'step = '+str(step)
##leg.texts.set_text(lab)
ims.append([im])##+leg])
ani = animation.ArtistAnimation(fig,ims,interval=interval_pause,repeat_delay=repeat_pause)
#ani.save('animate_evolution '+str(timer())+'.mp4')
plt.show()
如您所链接的问题所示,使用FuncAnimation
更容易。 这样就可以只更新一个图例和imshow图,而不必创建其中的几个图例。
由于目前尚不清楚图例应显示在imshow图中,因此我只创建了一个蓝色矩形。 您当然可以用自己喜欢的任何东西替换它。
import matplotlib.animation as animation
from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np
N=20
steps = 100
interval_pause = 100
repeat_pause = 1000
cmap = colors.ListedColormap(['white', 'black'])
bounds=[-1,0,1]
norm = colors.BoundaryNorm(bounds, cmap.N)
fig = plt.figure()
ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
ax.axes.xaxis.set_ticks([])
ax.axes.yaxis.set_ticks([])
array = 2*(np.random.rand(N,N,steps)-0.5)
leg = ax.legend([plt.Rectangle((0,0),1,1)],["step0"], loc='upper left',prop={'size':12})
img = ax.imshow(array[:,:,0],interpolation='nearest',cmap=cmap,norm=norm, animated=True)
fig.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[-1,0,1])
def update(step):
state = array[:,:,step]
img.set_data(state)
lab = 'step = '+str(step)
leg.texts[0].set_text(lab)
ani = animation.FuncAnimation(fig,update,frames = steps,
interval=interval_pause,repeat_delay=repeat_pause)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.