0

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)

enter image description here

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.

frames stacked on top of each other?

2
  • 1
    Welcome to Stack Overflow, please take the tour. Without a reproducible example we can only speculate. My immediate guess is that the plot method of whatever pr_image is adds a colorbar every time it is called and ax.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. Commented Apr 22, 2024 at 2:54
  • Additionally, the maximum value of the map changes with each time step. You should add the vmax-argument to a fixed maximum so changes are interpretable and one colorbar explains all datapoints. Commented Apr 25, 2024 at 13:54

1 Answer 1

0

try adding colourbar afterwards

...
pr_image.plot(ax=ax, add_colorbar=False)
...
cbar = fig.colorbar(pr_image.isel(time=0).plot())
#show or save animation

i has the same issue and answered my own question here

how to animation with xarray dataset and cartopy projection with a colorbar?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.