ncplot.netcdf_to_animation#
- class ncplot.netcdf_to_animation(data, output_path, *, variable_name=None, start_date=None, end_date=None, vmin=None, vmax=None, cmap='viridis', fps=2, figsize=(12, 8), title_template=None, mask_values=None, background_data=None, extent=None, dpi=100, bitrate=1800, **kwargs)[source]#
Convert NetCDF data to animated GIF or MP4.
This function creates animations from spatio-temporal NetCDF data without writing individual frame files to disk, using matplotlib’s animation capabilities.
Parameters#
- datapath (str or pathlib.Path) or xarray.Dataset
NetCDF data to animate. Can be a file path or loaded xarray Dataset.
- output_pathstr or pathlib.Path
Output path for the animation file. Format is determined by file extension (.gif or .mp4).
- variable_namestr, optional
Name of the variable to animate. If None, will use the main variable detected by geobricks.main_vars().
- start_datestr, optional
Start date for the animation in ‘YYYY-MM-DD’ format.
- end_datestr, optional
End date for the animation in ‘YYYY-MM-DD’ format.
- vmin, vmaxfloat, optional
Min/max values for color scaling. If None, computed from data.
- cmapstr or matplotlib colormap, default ‘viridis’
Colormap to use for visualization.
- fpsint, default 2
Frames per second for the animation.
- figsizetuple, default (12, 8)
Figure size in inches (width, height).
- title_templatestr, optional
Template for frame titles. Use {time} as placeholder for time values. Default: ‘{variable_name} - {time}’
- mask_valuestuple or list, optional
Range of values to mask (e.g., (-100, 100) to mask values between -100 and 100).
- background_datapath or xarray.Dataset, optional
Background data (e.g., DEM) to display under the main data. Only the portion corresponding to the data extent will be shown.
- extentlist or tuple, optional
Custom spatial extent [west, east, south, north] in the same CRS as the data. If None, uses the extent of the main data.
- dpiint, default 100
Resolution in dots per inch.
- bitrateint, default 1800
Bitrate in kbps (kilobits per second) for MP4 videos. Higher values = better quality but larger file size. Common values: 500 (low quality), 1800 (medium), 3500 (high). Only used for MP4 format, ignored for GIF.
- **kwargs
Additional arguments passed to matplotlib’s imshow or pcolormesh.
Returns#
- str
Path to the created animation file.
Notes#
This function uses matplotlib’s animation framework instead of saving individual frames to disk.
For very large datasets, consider pre-processing the data to reduce the temporal resolution (e.g., daily to monthly) before creating animations.
Inspired by johannesuhl/netcdf2mp4