Skip to content

Extra colorbar added for each call of function using plot helper #7288

Open
@MattF-NSIDC

Description

@MattF-NSIDC

What is your issue?

I can't tell right now whether this is a bug or a pitfall (i.e. I'm using xarray wrong) that I've encountered. If the latter, I'd be happy to help out documenting this for future users. I have not been able to reproduce this issue in the xarray Binder template (I don't know why), but was able to create a minimal reproducible example outside of a Jupyter context. Please reproduce from: https://github.com/MattF-NSIDC/sscce-xarray-plot-dup-colorbar

Simply load the page once to see the correct version of the image. Refresh the page, and each time a new colorbar will be added, ad infinitum.

image

Summary

I'm writing a web application that plots data stored in netcdf files using xarray. I'm using the following documentation to guide my decisions:

https://docs.xarray.dev/en/stable/user-guide/plotting.html#maps
https://matplotlib.org/stable/gallery/user_interfaces/web_application_server_sgskip.html

I'm:

  1. Plotting example air temp data using xarray's DataArray.plot method
  2. Saving the figure associated with the plot (plot.figure.savefig) to a BytesIO buffer
  3. Encoding bytes and displaying in an HTML image tag

When I do this, every refresh of the page adds a new colorbar. I don't think steps 2 and 3 are relevant to this issue; I think the important part is that repeated calls to the xarray plot helper are executed within the same Python process.

I can work around this by passing figsize=(width, height) to the plot method.

The xarray docs (linked above) offer a suggestion about why this happens:

If figsize or size are used, a new figure is created, so this is mutually exclusive with the ax argument.

And the matplot lib docs (linked above) offer another suggestion:

pyplot maintains references to the opened figures to make show work, but this will cause memory leaks unless the figures are properly closed

I wonder if this may have something to do with the stateful nature of matplotlib.pyplot?

Thanks for your time!
Matt

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions