I am trying to animate a plot using matplotlib's FuncAnimation, however it never outputs anything. The data is NetCDF, precipitation rates for the USA with coords for day, x and y. The x is longitude and y is latitude.
I've grouped the data by month and now I'm trying to create an animation where each frame is the mean precipitation rate for each location, for one month (e.g. the first frame is a map of the USA with a colour overlay showing precipitation rates for January)

Here is the code, I'm not sure how to get the animation to display correctly.
import rioxarray
import xarray
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fn = 'C:/.../pr_2020.nc'
pr = rioxarray.open_rasterio(fn)
pr_masked = pr.where(pr != pr.attrs['_FillValue'])
pr_monthly = pr_masked.groupby('day.month').mean()
fig, ax = plt.subplots()
def update(frame):
ax.clear()
pr_image = pr_monthly[frame, :, :]
pr_image.plot(ax=ax)
ax.set_title(f"Month: {frame}")
return ax
pr_image = pr_monthly[0, :, :]
pr_image.plot(ax=ax)
ax.set_title("Month: 0")
ani = FuncAnimation(fig, update, frames=len(pr_monthly['month']), interval=500)
plt.show()
If I save the animation it looks like all the frames have been stacked on top of each other.

plotmethod of whateverpr_imageis adds a colorbar every time it is called andax.clear()isn't clearing the colorbar axis.fig.clear()might help, but we need more if we are going to be able to help you.vmax-argument to a fixed maximum so changes are interpretable and one colorbar explains all datapoints.