0

I am trying to save the sequence of plots of 24 hours of ERA5 data from .nc file without plotting them. I am using xarray for reading .nc data. Here is my code:

import xarray as xr
import matplotlib.image as img

data = 'wind.nc'
DS = xr.open_dataset(data)['u10']
fig, ax = plt.subplots(1, 1, figsize=(7, 3.5))
for i in range(24):
    x = '2022-01-31T0' + str(i) + ':00'
    y = str(i) + '.PNG'
    DS.sel(time=x).plot(cmap='bone')
    plt.title('U Wind Component')
    plt.axis('off')
    plt.savefig(y, bbox_inches='tight')

Is there any way to accomplish this without showing the plots or any other library that does the job?

2

1 Answer 1

0

Writing plt.close(fig) at the end of your script should avoid the plot from showing, while still saving the figure.

However I believe there is another problem in your script. You create a fig and ax but in the loop they are not referenced so with every DS.plot() you create a new figure. Rather I would write it as follows:

for i in range(24):
    fig, ax = plt.subplots()
    x = '2022-01-31T0' + str(i) + ':00'
    y = str(i) + '.PNG'
    DS.sel(time=x).plot(ax = ax, cmap='bone')
    plt.title('U Wind Component')
    plt.axis('off')
    fig.savefig("figname.png", bbox_inches='tight')
    plt.close(fig)
2
  • Thanks, this solved the issue. I managed to remove the title as well but can't remove the color bar. How do I turnoff colorbar?
    – pwnkit
    Commented Mar 13, 2023 at 17:13
  • DS.plot(add_colorbar=False)
    – wpuma
    Commented Mar 13, 2023 at 18:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.