0

I made an animation of some netcdf data. I would love to save it without a border. Converting the saved .mov file to a gif (my ultimate goal), ffmpeg -i animation.mov animation.gif , leaves me with an animation that has much whitespace.

import xarray as xr
import matplotlib.pyplot as plt
from matplotlib import animation
import cartopy.crs as ccrs
import pandas as pd

plate = ccrs.PlateCarree()
equal_area = ccrs.AlbersEqualArea(central_latitude=39.8283, central_longitude=-98.5795)

ds = xr.tutorial.open_dataset('air_temperature')
ds = ds.sel(time=slice('2013-01-01', '2013-01-08'))

fig, ax = plt.subplots(figsize=(5, 5), dpi=300, subplot_kw=dict(projection=equal_area))

times = ds.time.values
first, times = times[0], times[1:]

mesh = ds['air'].sel(time=first) \
    .plot(
        cmap='viridis', 
        ax=ax,
        transform = plate,
        add_colorbar=False
)
ax.set_title(pd.to_datetime(first.item()).strftime('%b. %-d, %Y'))

ax.spines[:].set_visible(False)
    
ax.coastlines(color='gray', lw=0.5, alpha=0.4)

ax.set_extent([-120, -73, 25, 49], plate)

gl = ax.gridlines(linewidth=0.5, color='black', alpha=0.5, linestyle='--', draw_labels=True)
gl.top_labels = False
gl.right_labels = False
style = {'size': 8}
gl.xlabel_style = style
gl.ylabel_style = style

def animate(frame):
    mesh.set_array(ds['air'].sel(time=ds.time.values[frame]).values.flatten())
    ax.set_title(pd.to_datetime(ds.time[frame].item()).strftime('%b. %-d, %Y'))

ani = animation.FuncAnimation(
    fig,
    animate,
    frames=ds.time.values.size,
    interval=200
)

ani.save('animation.mov')

enter image description here

I also tried saving with zero padding ani.save('animation.mov', savefig_kwargs=dict(pad_inches=0), but the dimensions and file size are the exact same.

I also tried placing the axes in the the full figure size like this

fig = plt.figure(frameon=False, dpi=300)
fig.set_size_inches(5,5)

ax = fig.add_axes([0.1, 0., 1., 1.], projection=equal_area)
ax.set_axis_off()

# rest of the plotting code

that creates something that is a little better, but now the quality is very bad.

enter image description here

What else can I do to reduce this size but also keep the resolution?

I do know that the easiest solution here is to make the full-resolution .mov file and then use a tool like ezgif (pronounced properly with a hard g) to crop the thing, but that seems to transform the background into an off white color.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
K. Shores
  • 875
  • 1
  • 18
  • 46

0 Answers0