matplotlib / basemap

Plot on map projections (with coastlines and political boundaries) using matplotlib
MIT License
779 stars 392 forks source link

Basemap overdrawing #432

Closed DavidEscott closed 6 years ago

DavidEscott commented 6 years ago

Basemap sits around in global memory even when it is out of scope, and then attaches to the current figure and draws itself repeatedly. This is most noticeable when writing the output to pdfpages. See the attached script (uploaded as a txt since .py isn't supported).

The script repeatedly calls a function which draws the state outline and saves the output to a pdf, each time incrementing the file name "test0.pdf" then "test1.pdf" then "test2.pdf", etc...

The first file test0.pdf will be 131KB, then test1.pdf will be 253KB since it includes the overdraw of the previous file, and so on...

This is with basemap 1.2.0 installed with anaconda (build py37h705c2d8_0), matplotlib 3.0.0 (build py37h5429711_0) Python 3.7.0 (build h6e4f718_3)

basemap_bug.txt

WeatherGod commented 6 years ago

This is not a basemap bug, but a mis-understanding of how matplotlib's pyplot interface works. Figures created via the pyplot interface don't automatically close when they go out of scope. You have to explicitly close them yourself.

Generally, good practice when you have a function that is doing plotting is to pass the axes object to that function (and don't use plt within that function!). The code that calls the function can assume responsibility for creating (via plt.gcf() for example) and destroying the figure (via fig.close())

WeatherGod commented 6 years ago

Sorry, correction, not fig.close(), but rather plt.close(fig)