Last active
October 24, 2022 15:49
-
-
Save ScottWales/5d0ef918d56c4f6f58b73c1d5eabaf9b to your computer and use it in GitHub Desktop.
Animated xarray+cartopy plot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from __future__ import print_function | |
import xarray | |
import matplotlib.pyplot as plt | |
import cartopy.crs as ccrs | |
import matplotlib.animation as anim | |
import cartopy | |
filenames = ['/g/data3/w97/dc8106/AMZ_def_EXPs/121GPsc_E0/AMZDEF.daily_tasmax.1978_2011_121GPsc_E0_SAmerica.nc'] | |
# Load files | |
data = xarray.open_mfdataset(filenames) | |
# Nomalise the longitude into [-180, 180) | |
data['lon'] = data['lon'] - 360 | |
# Select the variable & region of interest | |
variable = data.tasmax.sel(time=slice('1996', '1998')) | |
# Setup the initial plot | |
fig = plt.figure() | |
ax = plt.axes(projection=ccrs.PlateCarree()) | |
# Set up levels etc in this call | |
image = variable.isel(time = 0).plot.imshow(ax=ax, transform=ccrs.PlateCarree(), animated=True) | |
# Set up static features - coastlines, political borders etc. | |
ax.coastlines() | |
def update(t): | |
# Update the plot for a specific time | |
print(t) | |
ax.set_title("time = %s"%t) | |
image.set_array(variable.sel(time=t)) | |
return image, | |
# Run the animation, applying `update()` for each of the times in the variable | |
animation = anim.FuncAnimation(fig, update, frames=variable.time.values, blit=False) | |
# Save to file or display on screen | |
#animation.save('tasmax.mp4', fps=30, extra_args=['-vcodec', 'libx264']) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment