python - 使用 matplotlib 动画更新 x 轴值

标签 python animation matplotlib

我正在尝试使用 matplotlib.ArtistAnimation 为两个子图制作动画。我希望 x 轴的值随着动画的进行而增加,这样动画的总长度为 100,但在任何时候子图只向我显示 0-24 的时间值,然后迭代到 100。

给出了一个很好的例子here .该链接使用 FuncAnimation 并使用 plot().axes.set_xlim() 以滚动方式更新 x 轴标签并增加 x 值。该代码可通过提供的链接中 YouTube 视频下方的链接获得。

我在下面附加了代码,显示了我尝试复制这些结果的尝试,但 x 限制似乎采用了它们的最终值,而不是随时间递增。我还尝试通过仅绘制将在子图中看到的窗口中的值来增加解决方案(而不是轴),但这不会增加 x 轴值。我也尝试实现自动缩放,但 x 轴仍然没有更新。

我还找到了this question这实际上是同一个问题,但问题从未得到解答。

这是我的代码:

import matplotlib.pylab as plt
import matplotlib.animation as anim
import numpy as np

#create image with format (time,x,y)
image = np.random.rand(100,10,10)

#setup figure
fig = plt.figure()
ax1=fig.add_subplot(1,2,1)
ax2=fig.add_subplot(1,2,2)
#set up viewing window (in this case the 25 most recent values)
repeat_length = (np.shape(image)[0]+1)/4
ax2.set_xlim([0,repeat_length])
#ax2.autoscale_view()
ax2.set_ylim([np.amin(image[:,5,5]),np.amax(image[:,5,5])])

#set up list of images for animation

ims=[]
for time in xrange(np.shape(image)[0]):

    im = ax1.imshow(image[time,:,:])
    im2, = ax2.plot(image[0:time,5,5],color=(0,0,1))
    if time>repeat_length:
        lim = ax2.set_xlim(time-repeat_length,time)

    ims.append([im, im2])


#run animation
ani = anim.ArtistAnimation(fig,ims, interval=50,blit=False)
plt.show()

我只希望第二个子图 (ax2) 更新 x 轴值。

如有任何帮助,我们将不胜感激。

最佳答案

如果你需要blitting

import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np

#create image with format (time,x,y)
image = np.random.rand(100,10,10)

#setup figure
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
#set up viewing window (in this case the 25 most recent values)
repeat_length = (np.shape(image)[0]+1)/4
ax2.set_xlim([0,repeat_length])
#ax2.autoscale_view()
ax2.set_ylim([np.amin(image[:,5,5]),np.amax(image[:,5,5])])

#set up list of images for animation


im = ax1.imshow(image[0,:,:])
im2, = ax2.plot([], [], color=(0,0,1))

def func(n):
    im.set_data(image[n,:,:])

    im2.set_xdata(np.arange(n))
    im2.set_ydata(image[0:n, 5, 5])
    if n>repeat_length:
        lim = ax2.set_xlim(n-repeat_length, n)
    else:
        # makes it look ok when the animation loops
        lim = ax2.set_xlim(0, repeat_length)
    return im, im2

ani = animation.FuncAnimation(fig, func, frames=image.shape[0], interval=30, blit=False)

plt.show()

会起作用。

如果您需要跑得更快,您将需要使用用于 blitting 的边界框来玩游戏,以便更新轴标签。

关于python - 使用 matplotlib 动画更新 x 轴值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17895698/

相关文章:

python - 如何通过在一个函数中包含所有类型的填充来处理缺失值?

python - 目标 WSGI 脚本 '/opt/python/current/app/.../wsgi.py' 无法作为 Python 模块加载

python - Pandas groupby将不连续的视为不同的变量?

html - CSS 关键帧 - 缩放和平移

将鼠标悬停在容器上时 CSS 转换图像

python - 使用 python 根据条件对绘图进行颜色填充

python - 从字典中重新编码 Pandas 索引对象(用于无序替换)

javascript - 如何使视口(viewport)跟随此 javascript 代码中的矩形?

python - 使用 scipy.interpolate.griddata 时如何设置插值点之间的最大距离?

python - 将stft转换为色度并绘制结果