如何使用 xarray 数据集制作动画并将其投影到包含颜色条的 PlateCarree 投影上?
我花了一些时间试图回答这个问题,堆栈溢出其他地方的一些其他答案很有用,但不完整。
我正在回答我自己的问题,以供我自己和其他人(如果他们觉得有用的话)参考
import xarray as xr
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import cartopy.crs as ccrs
# open the tutorial data
ds = xr.tutorial.load_dataset('air_temperature')
# Create a new figure
fig = plt.figure()
# Create an axes for the plot with the cartopy PlateCarree projection
ax = plt.axes(projection=ccrs.PlateCarree())
#arguments
plot_args = {
'transform':ccrs.PlateCarree(),
'vmin': ds.air.quantile(0.01), # 1st percentile
'vmax': ds.air.quantile(0.99),
'cmap': 'RdBu_r',
'add_colorbar': False #important otherwise replots multitude of colorbars
}
default_gridlines_kw = {'linewidth' : 1.5,
'color' : 'silver',
'alpha': 0.5,
'linestyle':'--',
'xlabel_style': {'size':8},
'ylabel_style': {'size':8}
}
# Define an update function that will be called for each frame
def animate(frame):
ax.clear()# can be necessary if some areas are nan... but unnecessary with the tutorial complete dataset without any gaps
# ax.set_facecolor('darkslategray') # another useful parameter when some areas are nan, unnecesaary with the tutorial dataset
ds.air.isel(time=frame).plot(ax=ax, **plot_args)
ax.coastlines()
# to draw the gridline in cartopy you need to tell it what projection you are using
#but also you need to tell it to draw_labels=True as some projections don't have them
#or are confusing to draw
ax.gridlines(draw_labels=True, **default_gridlines_kw)
# Create the animation
ani = animation.FuncAnimation(fig, animate, frames=range(100), interval=200, repeat=True)
#define the colorbar. The colorbar method needs a mappable object from which to take the colorbar
cbar = fig.colorbar(ds.air.isel(time=0).plot(**plot_args))
# Save the animation as an mp4 file
ani.save('myanimation.mp4', writer='ffmpeg')