【问题标题】:Matplotlib animation with Xarray data带有 Xarray 数据的 Matplotlib 动画
【发布时间】:2022-06-15 18:32:43
【问题描述】:

我已经坚持了一段时间了。我尝试绘制我的数据并为 12 帧设置动画。 这就是我的代码现在的样子。

import xarray as xr
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.animation as animation
from IPython.display import HTML


url = 'https://username:password@nrt.cmems-du.eu/thredds/dodsC/global-analysis-forecast-phy-001-024-monthly?latitude[0:1:2040],longitude[0:1:4319],depth[0:1:49],time[0:1:34],mlotst[0:1:34][0:1:2040][0:1:4319]'
ds = xr.open_dataset(url)
ds.to_netcdf('mlotst.nc') #Make a netcdf-file

cond = (ds.latitude>22) & (ds.latitude<30.5) & (ds.longitude>47) & (ds.longitude<63)
ds = ds.where(cond,drop=True) #Narrowing it down to the coordinates I want

fig = plt.figure(figsize=(10,6))
#ax = plt.axes(xlim=(47, 63), ylim=(22, 31))
levels = range(90)


def animate(time):
    plt.clf()
    fig = ds.isel(time=time).mlotst.plot(levels=levels, figsize=(10,6))

ani = animation.FuncAnimation(fig, animate, range(13), interval=200, blit=False)
plt.show()


FFwriter = animation.FFMpegWriter()
ani.save('anim.mp4', writer = FFwriter)

它只是变成白色的。请帮忙。

【问题讨论】:

  • 每次拨打animate,您都在制作一个新人物。建议您制作一个轴并将其传递给plot
  • 所以我应该先创建空轴,然后以某种方式将图形传递给它?..你对我如何在我的函数中得到这个有什么建议吗?感谢您的回答
  • 当然,只需传入.plot(levels=levels, ax=ax),其中ax 是您的坐标轴。您可以将ax 作为farg 传递给FuncAnimation,或者更简单地使其成为全局
  • 我想我在你的帮助下搞定了!经过 24 小时的努力,非常感谢 :)
  • 我的动画中的颜色条有问题。我想为我所有的动画人物保留第一个颜色条。我尝试通过设置 add_colorbar = time ==0 来做到这一点,如仅用于 tilmestep 0。但这给了我两个颜色条。因此,当我为 tilmestep 1 执行此操作时,我只得到一个颜色条(就像我想要的那样),但不是动画中的第一帧(第 0 帧)。有什么快速解决办法吗?

标签: python matplotlib animation python-xarray


【解决方案1】:

不久前我写了这个问题,但我刚刚看到一条评论,想知道解决方案。基本上定义 ax =axes 是“只是”,然后我工作了

工作代码:

levels = range(90)
fig, axes = plt.subplots(figsize=[11,8])#ncols=1) #Creating the basis for the plot

def animate(time):
    ds.isel(time=time).mlotst.plot.contourf(levels=levels, ax=axes, add_colorbar= False)

ani = animation.FuncAnimation(fig, animate, 24, interval=400, blit=False)


mld= ds.isel(time=0).mlotst.plot.contourf(levels=levels, ax=axes, add_colorbar= False)
cbar= fig.colorbar(mld)
cbar.set_label('Mixed layer thickness [m]')
fig.suptitle("Mixed layer thickness transect. Persian Gulf and Gulf of Oman Jan -19 to Dec -20", fontsize= 18)

#ani.save('animation.gif', writer='imagemagick', fps = 2) #Save animation as gif-file

HTML(ani.to_jshtml()) #Show the animation in the kernel

希望这对将来的人有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2013-05-24
    • 2018-01-08
    • 2015-11-23
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多