Repository: SciTools/cartopy

Issue:
Using Gridliner in Jupyter notebooks with `%matplotlib inline` crashes
### Description

I am attempting to make some plots in Jupyter notebooks using matplotlib and cartopy. I would like to include geoaxes on these. Adding the following code to a notebook will throw an error.

#### Code to reproduce

Set up a fresh conda environment, install the required libraries, and run jupyter-lab

```shell
$ conda install -c conda-forge cartopy=0.22 matplotlib=3.8 python=3.11 jupyterlab=4.0
$ jupyter-lab
```

Make a new notebook and add this code:

```python
%matplotlib inline

import cartopy.crs
import numpy
from matplotlib import pyplot as plt
from matplotlib.collections import PolyCollection

figure = plt.figure(figsize=(8, 6), dpi=100)
axes = figure.add_subplot(projection=cartopy.crs.PlateCarree())
axes.set_aspect(aspect='equal', adjustable='datalim')
axes.set(title="botz")

collection = PolyCollection(
    verts=[
        [[151, -23], [152, -23], [151, -22], [150, -22]]
    ],
    array=[0],
    cmap='jet',
    edgecolor='face',
)
axes.add_collection(collection)

gridlines = axes.gridlines(draw_labels=["bottom", "left"], auto_update=True)

axes.autoscale()
```

The error is not present if I change any of the following:

* Remove the `draw_labels=[...]` parameter to `axes.gridlines()`. However I need grid labels here.
* Remove the `auto_update=True` parameter to `axes.gridlines()`. `auto_update=True` is useful for interactive backends though, so I'd prefer to keep it enabled. If there was some good way of detecting interactive backends I could update the code to use that instead of defaulting to True. However even with `%matplotlib inline`, `matplotlib.pyplot.isinteractive()` returns True.

#### Traceback

```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/IPython/core/formatters.py:340, in BaseFormatter.__call__(self, obj)
    338     pass
    339 else:
--> 340     return printer(obj)
    341 # Finally look for special method names
    342 method = get_real_method(obj, self.print_method)

File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/IPython/core/pylabtools.py:152, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
    149     from matplotlib.backend_bases import FigureCanvasBase
    150     FigureCanvasBase(fig)
--> 152 fig.canvas.print_figure(bytes_io, **kw)
    153 data = bytes_io.getvalue()
    154 if fmt == 'svg':

File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/matplotlib/backend_bases.py:2161, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2159 if bbox_inches:
   2160     if bbox_inches == "tight":
-> 2161         bbox_inches = self.figure.get_tightbbox(
   2162             renderer, bbox_extra_artists=bbox_extra_artists)
   2163         if (isinstance(layout_engine, ConstrainedLayoutEngine) and
   2164                 pad_inches == "layout"):
   2165             h_pad = layout_engine.get()["h_pad"]

File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only.<locals>.wrapper(*args, **kwargs)
    448 if len(args) > name_idx:
    449     warn_deprecated(
    450         since, message="Passing the %(name)s %(obj_type)s "
    451         "positionally is deprecated since Matplotlib %(since)s; the "
    452         "parameter will become keyword-only %(removal)s.",
    453         name=name, obj_type=f"parameter of {func.__name__}()")
--> 454 return func(*args, **kwargs)

File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/matplotlib/figure.py:1774, in FigureBase.get_tightbbox(self, renderer, bbox_extra_artists)
   1771     artists = bbox_extra_artists
   1773 for a in artists:
-> 1774     bbox = a.get_tightbbox(renderer)
   1775     if bbox is not None:
   1776         bb.append(bbox)

File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/matplotlib/artist.py:366, in Artist.get_tightbbox(self, renderer)
    350 def get_tightbbox(self, renderer=None):
    351     """
    352     Like `.Artist.get_window_extent`, but includes any clipping.
    353 
   (...)
    364         Returns None if clipping results in no intersection.
    365     """
--> 366     bbox = self.get_window_extent(renderer)
    367     if self.get_clip_on():
    368         clip_box = self.get_clip_box()

File ~/hecking-around/emsarray/.conda/lib/python3.11/site-packages/matplotlib/text.py:940, in Text.get_window_extent(self, renderer, dpi)
    938     return Bbox.unit()
    939 if dpi is None:
--> 940     dpi = self.figure.dpi
    941 if self.get_text() == '':
    942     with cbook._setattr_cm(self.figure, dpi=dpi):

AttributeError: 'NoneType' object has no attribute 'dpi'
```

<details>
 <summary>Full environment definition</summary>

<!-- fill in the following information as appropriate -->

### Operating system

Ubuntu 20.04

### Cartopy version

0.22.0

### conda list

```
# packages in environment at /home/hea211/hecking-around/emsarray/.conda:
#
# Name                    Version                   Build  Channel
_libgcc_mutex             0.1                 conda_forge    conda-forge
_openmp_mutex             4.5                       2_gnu    conda-forge
alsa-lib                  1.2.10               hd590300_0    conda-forge
anyio                     4.0.0              pyhd8ed1ab_0    conda-forge
argon2-cffi               23.1.0             pyhd8ed1ab_0    conda-forge
argon2-cffi-bindings      21.2.0          py311hd4cff14_3    conda-forge
arrow                     1.2.3              pyhd8ed1ab_0    conda-forge
asttokens                 2.4.0              pyhd8ed1ab_0    conda-forge
async-lru                 2.0.4              pyhd8ed1ab_0    conda-forge
attr                      2.5.1                h166bdaf_1    conda-forge
attrs                     23.1.0             pyh71513ae_1    conda-forge
babel                     2.12.1             pyhd8ed1ab_1    conda-forge
backcall                  0.2.0              pyh9f0ad1d_0    conda-forge
backports                 1.0                pyhd8ed1ab_3    conda-forge
backports.functools_lru_cache 1.6.5              pyhd8ed1ab_0    conda-forge
beautifulsoup4            4.12.2             pyha770c72_0    conda-forge
bleach                    6.0.0              pyhd8ed1ab_0    conda-forge
brotli                    1.1.0                hd590300_0    conda-forge
brotli-bin                1.1.0                hd590300_0    conda-forge
brotli-python             1.1.0           py311hb755f60_0    conda-forge
bzip2                     1.0.8                h7f98852_4    conda-forge
c-ares                    1.19.1               hd590300_0    conda-forge
ca-certificates           2023.7.22            hbcca054_0    conda-forge
cached-property           1.5.2                hd8ed1ab_1    conda-forge
cached_property           1.5.2              pyha770c72_1    conda-forge
cairo                     1.16.0            h0c91306_1017    conda-forge
cartopy                   0.22.0          py311h320fe9a_0    conda-forge
certifi                   2023.7.22          pyhd8ed1ab_0    conda-forge
cffi                      1.15.1          py311h409f033_3    conda-forge
charset-normalizer        3.2.0              pyhd8ed1ab_0    conda-forge
comm                      0.1.4              pyhd8ed1ab_0    conda-forge
contourpy                 1.1.1           py311h9547e67_0    conda-forge
cycler                    0.11.0             pyhd8ed1ab_0    conda-forge
dbus                      1.13.6               h5008d03_3    conda-forge
debugpy                   1.8.0           py311hb755f60_0    conda-forge
decorator                 5.1.1              pyhd8ed1ab_0    conda-forge
defusedxml                0.7.1              pyhd8ed1ab_0    conda-forge
entrypoints               0.4                pyhd8ed1ab_0    conda-forge
exceptiongroup            1.1.3              pyhd8ed1ab_0    conda-forge
executing                 1.2.0              pyhd8ed1ab_0    conda-forge
expat                     2.5.0                hcb278e6_1    conda-forge
font-ttf-dejavu-sans-mono 2.37                 hab24e00_0    conda-forge
font-ttf-inconsolata      3.000                h77eed37_0    conda-forge
font-ttf-source-code-pro  2.038                h77eed37_0    conda-forge
font-ttf-ubuntu           0.83                 hab24e00_0    conda-forge
fontconfig                2.14.2               h14ed4e7_0    conda-forge
fonts-conda-ecosystem     1                             0    conda-forge
fonts-conda-forge         1                             0    conda-forge
fonttools                 4.42.1          py311h459d7ec_0    conda-forge
fqdn                      1.5.1              pyhd8ed1ab_0    conda-forge
freetype                  2.12.1               h267a509_2    conda-forge
geos                      3.12.0               h59595ed_0    conda-forge
gettext                   0.21.1               h27087fc_0    conda-forge
glib                      2.78.0               hfc55251_0    conda-forge
glib-tools                2.78.0               hfc55251_0    conda-forge
graphite2                 1.3.13            h58526e2_1001    conda-forge
gst-plugins-base          1.22.5               h8e1006c_1    conda-forge
gstreamer                 1.22.5               h98fc4e7_1    conda-forge
harfbuzz                  8.2.1                h3d44ed6_0    conda-forge
icu                       73.2                 h59595ed_0    conda-forge
idna                      3.4                pyhd8ed1ab_0    conda-forge
importlib-metadata        6.8.0              pyha770c72_0    conda-forge
importlib_metadata        6.8.0                hd8ed1ab_0    conda-forge
importlib_resources       6.0.1              pyhd8ed1ab_0    conda-forge
ipykernel                 6.25.2             pyh2140261_0    conda-forge
ipympl                    0.9.3              pyhd8ed1ab_0    conda-forge
ipython                   8.15.0             pyh0d859eb_0    conda-forge
ipython_genutils          0.2.0                      py_1    conda-forge
ipywidgets                8.1.1              pyhd8ed1ab_0    conda-forge
isoduration               20.11.0            pyhd8ed1ab_0    conda-forge
jedi                      0.19.0             pyhd8ed1ab_0    conda-forge
jinja2                    3.1.2              pyhd8ed1ab_1    conda-forge
json5                     0.9.14             pyhd8ed1ab_0    conda-forge
jsonpointer               2.4             py311h38be061_2    conda-forge
jsonschema                4.19.0             pyhd8ed1ab_1    conda-forge
jsonschema-specifications 2023.7.1           pyhd8ed1ab_0    conda-forge
jsonschema-with-format-nongpl 4.19.0             pyhd8ed1ab_1    conda-forge
jupyter-lsp               2.2.0              pyhd8ed1ab_0    conda-forge
jupyter_client            8.3.1              pyhd8ed1ab_0    conda-forge
jupyter_core              5.3.1           py311h38be061_0    conda-forge
jupyter_events            0.7.0              pyhd8ed1ab_2    conda-forge
jupyter_server            2.7.3              pyhd8ed1ab_0    conda-forge
jupyter_server_terminals  0.4.4              pyhd8ed1ab_1    conda-forge
jupyterlab                4.0.6              pyhd8ed1ab_0    conda-forge
jupyterlab_pygments       0.2.2              pyhd8ed1ab_0    conda-forge
jupyterlab_server         2.25.0             pyhd8ed1ab_0    conda-forge
jupyterlab_widgets        3.0.9              pyhd8ed1ab_0    conda-forge
keyutils                  1.6.1                h166bdaf_0    conda-forge
kiwisolver                1.4.5           py311h9547e67_0    conda-forge
krb5                      1.21.2               h659d440_0    conda-forge
lame                      3.100             h166bdaf_1003    conda-forge
lcms2                     2.15                 h7f713cb_2    conda-forge
ld_impl_linux-64          2.40                 h41732ed_0    conda-forge
lerc                      4.0.0                h27087fc_0    conda-forge
libblas                   3.9.0           18_linux64_openblas    conda-forge
libbrotlicommon           1.1.0                hd590300_0    conda-forge
libbrotlidec              1.1.0                hd590300_0    conda-forge
libbrotlienc              1.1.0                hd590300_0    conda-forge
libcap                    2.69                 h0f662aa_0    conda-forge
libcblas                  3.9.0           18_linux64_openblas    conda-forge
libclang                  15.0.7          default_h7634d5b_3    conda-forge
libclang13                15.0.7          default_h9986a30_3    conda-forge
libcups                   2.3.3                h4637d8d_4    conda-forge
libcurl                   8.3.0                hca28451_0    conda-forge
libdeflate                1.19                 hd590300_0    conda-forge
libedit                   3.1.20191231         he28a2e2_2    conda-forge
libev                     4.33                 h516909a_1    conda-forge
libevent                  2.1.12               hf998b51_1    conda-forge
libexpat                  2.5.0                hcb278e6_1    conda-forge
libffi                    3.4.2                h7f98852_5    conda-forge
libflac                   1.4.3                h59595ed_0    conda-forge
libgcc-ng                 13.2.0               h807b86a_1    conda-forge
libgcrypt                 1.10.1               h166bdaf_0    conda-forge
libgfortran-ng            13.2.0               h69a702a_1    conda-forge
libgfortran5              13.2.0               ha4646dd_1    conda-forge
libglib                   2.78.0               hebfc3b9_0    conda-forge
libgomp                   13.2.0               h807b86a_1    conda-forge
libgpg-error              1.47                 h71f35ed_0    conda-forge
libiconv                  1.17                 h166bdaf_0    conda-forge
libjpeg-turbo             2.1.5.1              hd590300_1    conda-forge
liblapack                 3.9.0           18_linux64_openblas    conda-forge
libllvm15                 15.0.7               h5cf9203_3    conda-forge
libnghttp2                1.52.0               h61bc06f_0    conda-forge
libnsl                    2.0.0                h7f98852_0    conda-forge
libogg                    1.3.4                h7f98852_1    conda-forge
libopenblas               0.3.24          pthreads_h413a1c8_0    conda-forge
libopus                   1.3.1                h7f98852_1    conda-forge
libpng                    1.6.39               h753d276_0    conda-forge
libpq                     15.4                 hfc447b1_0    conda-forge
libsndfile                1.2.2                hbc2eb40_0    conda-forge
libsodium                 1.0.18               h36c2ea0_1    conda-forge
libsqlite                 3.43.0               h2797004_0    conda-forge
libssh2                   1.11.0               h0841786_0    conda-forge
libstdcxx-ng              13.2.0               h7e041cc_1    conda-forge
libsystemd0               254                  h3516f8a_0    conda-forge
libtiff                   4.6.0                h29866fb_1    conda-forge
libuuid                   2.38.1               h0b41bf4_0    conda-forge
libvorbis                 1.3.7                h9c3ff4c_0    conda-forge
libwebp-base              1.3.2                hd590300_0    conda-forge
libxcb                    1.15                 h0b41bf4_0    conda-forge
libxkbcommon              1.5.0                h5d7e998_3    conda-forge
libxml2                   2.11.5               h232c23b_1    conda-forge
libzlib                   1.2.13               hd590300_5    conda-forge
lz4-c                     1.9.4                hcb278e6_0    conda-forge
markupsafe                2.1.3           py311h459d7ec_0    conda-forge
matplotlib                3.8.0           py311h38be061_0    conda-forge
matplotlib-base           3.8.0           py311h54ef318_0    conda-forge
matplotlib-inline         0.1.6              pyhd8ed1ab_0    conda-forge
mistune                   3.0.1              pyhd8ed1ab_0    conda-forge
mpg123                    1.31.3               hcb278e6_0    conda-forge
munkres                   1.1.4              pyh9f0ad1d_0    conda-forge
mysql-common              8.0.33               hf1915f5_4    conda-forge
mysql-libs                8.0.33               hca2cd23_4    conda-forge
nbclient                  0.8.0              pyhd8ed1ab_0    conda-forge
nbconvert-core            7.8.0              pyhd8ed1ab_0    conda-forge
nbformat                  5.9.2              pyhd8ed1ab_0    conda-forge
ncurses                   6.4                  hcb278e6_0    conda-forge
nest-asyncio              1.5.6              pyhd8ed1ab_0    conda-forge
notebook-shim             0.2.3              pyhd8ed1ab_0    conda-forge
nspr                      4.35                 h27087fc_0    conda-forge
nss                       3.92                 h1d7d5a4_0    conda-forge
numpy                     1.26.0          py311h64a7726_0    conda-forge
openjpeg                  2.5.0                h488ebb8_3    conda-forge
openssl                   3.1.2                hd590300_0    conda-forge
overrides                 7.4.0              pyhd8ed1ab_0    conda-forge
packaging                 23.1               pyhd8ed1ab_0    conda-forge
pandocfilters             1.5.0              pyhd8ed1ab_0    conda-forge
parso                     0.8.3              pyhd8ed1ab_0    conda-forge
pcre2                     10.40                hc3806b6_0    conda-forge
pexpect                   4.8.0              pyh1a96a4e_2    conda-forge
pickleshare               0.7.5                   py_1003    conda-forge
pillow                    10.0.1          py311h8aef010_0    conda-forge
pip                       23.2.1             pyhd8ed1ab_0    conda-forge
pixman                    0.40.0               h36c2ea0_0    conda-forge
pkgutil-resolve-name      1.3.10             pyhd8ed1ab_1    conda-forge
platformdirs              3.10.0             pyhd8ed1ab_0    conda-forge
ply                       3.11                       py_1    conda-forge
proj                      8.2.1                ha227179_0  
prometheus_client         0.17.1             pyhd8ed1ab_0    conda-forge
prompt-toolkit            3.0.39             pyha770c72_0    conda-forge
prompt_toolkit            3.0.39               hd8ed1ab_0    conda-forge
psutil                    5.9.5           py311h2582759_0    conda-forge
pthread-stubs             0.4               h36c2ea0_1001    conda-forge
ptyprocess                0.7.0              pyhd3deb0d_0    conda-forge
pulseaudio-client         16.1                 hb77b528_5    conda-forge
pure_eval                 0.2.2              pyhd8ed1ab_0    conda-forge
pycparser                 2.21               pyhd8ed1ab_0    conda-forge
pygments                  2.16.1             pyhd8ed1ab_0    conda-forge
pyparsing                 3.1.1              pyhd8ed1ab_0    conda-forge
pyproj                    3.4.1           py311h93e2b2c_0  
pyqt                      5.15.9          py311hf0fb5b6_4    conda-forge
pyqt5-sip                 12.12.2         py311hb755f60_4    conda-forge
pyshp                     2.3.1              pyhd8ed1ab_0    conda-forge
pysocks                   1.7.1              pyha2e5f31_6    conda-forge
python                    3.11.5          hab00c5b_0_cpython    conda-forge
python-dateutil           2.8.2              pyhd8ed1ab_0    conda-forge
python-fastjsonschema     2.18.0             pyhd8ed1ab_0    conda-forge
python-json-logger        2.0.7              pyhd8ed1ab_0    conda-forge
python_abi                3.11                    3_cp311    conda-forge
pytz                      2023.3.post1       pyhd8ed1ab_0    conda-forge
pyyaml                    6.0.1           py311h459d7ec_0    conda-forge
pyzmq                     25.1.1          py311h75c88c4_0    conda-forge
qt-main                   5.15.8              hc47bfe8_16    conda-forge
readline                  8.2                  h8228510_1    conda-forge
referencing               0.30.2             pyhd8ed1ab_0    conda-forge
requests                  2.31.0             pyhd8ed1ab_0    conda-forge
rfc3339-validator         0.1.4              pyhd8ed1ab_0    conda-forge
rfc3986-validator         0.1.1              pyh9f0ad1d_0    conda-forge
rpds-py                   0.10.3          py311h46250e7_0    conda-forge
send2trash                1.8.2              pyh41d4057_0    conda-forge
setuptools                68.2.2             pyhd8ed1ab_0    conda-forge
shapely                   2.0.1           py311he06c224_2    conda-forge
sip                       6.7.11          py311hb755f60_0    conda-forge
six                       1.16.0             pyh6c4a22f_0    conda-forge
sniffio                   1.3.0              pyhd8ed1ab_0    conda-forge
soupsieve                 2.5                pyhd8ed1ab_1    conda-forge
sqlite                    3.43.0               h2c6b66d_0    conda-forge
stack_data                0.6.2              pyhd8ed1ab_0    conda-forge
terminado                 0.17.1             pyh41d4057_0    conda-forge
tinycss2                  1.2.1              pyhd8ed1ab_0    conda-forge
tk                        8.6.12               h27826a3_0    conda-forge
toml                      0.10.2             pyhd8ed1ab_0    conda-forge
tomli                     2.0.1              pyhd8ed1ab_0    conda-forge
tornado                   6.3.3           py311h459d7ec_0    conda-forge
traitlets                 5.10.0             pyhd8ed1ab_0    conda-forge
typing-extensions         4.8.0                hd8ed1ab_0    conda-forge
typing_extensions         4.8.0              pyha770c72_0    conda-forge
typing_utils              0.1.0              pyhd8ed1ab_0    conda-forge
tzdata                    2023c                h71feb2d_0    conda-forge
uri-template              1.3.0              pyhd8ed1ab_0    conda-forge
urllib3                   2.0.4              pyhd8ed1ab_0    conda-forge
wcwidth                   0.2.6              pyhd8ed1ab_0    conda-forge
webcolors                 1.13               pyhd8ed1ab_0    conda-forge
webencodings              0.5.1              pyhd8ed1ab_2    conda-forge
websocket-client          1.6.3              pyhd8ed1ab_0    conda-forge
wheel                     0.41.2             pyhd8ed1ab_0    conda-forge
widgetsnbextension        4.0.9              pyhd8ed1ab_0    conda-forge
xcb-util                  0.4.0                hd590300_1    conda-forge
xcb-util-image            0.4.0                h8ee46fc_1    conda-forge
xcb-util-keysyms          0.4.0                h8ee46fc_1    conda-forge
xcb-util-renderutil       0.3.9                hd590300_1    conda-forge
xcb-util-wm               0.4.1                h8ee46fc_1    conda-forge
xkeyboard-config          2.39                 hd590300_0    conda-forge
xorg-kbproto              1.0.7             h7f98852_1002    conda-forge
xorg-libice               1.1.1                hd590300_0    conda-forge
xorg-libsm                1.2.4                h7391055_0    conda-forge
xorg-libx11               1.8.6                h8ee46fc_0    conda-forge
xorg-libxau               1.0.11               hd590300_0    conda-forge
xorg-libxdmcp             1.1.3                h7f98852_0    conda-forge
xorg-libxext              1.3.4                h0b41bf4_2    conda-forge
xorg-libxrender           0.9.11               hd590300_0    conda-forge
xorg-renderproto          0.11.1            h7f98852_1002    conda-forge
xorg-xextproto            7.3.0             h0b41bf4_1003    conda-forge
xorg-xf86vidmodeproto     2.3.1             h7f98852_1002    conda-forge
xorg-xproto               7.0.31            h7f98852_1007    conda-forge
xz                        5.2.6                h166bdaf_0    conda-forge
yaml                      0.2.5                h7f98852_2    conda-forge
zeromq                    4.3.4                h9c3ff4c_1    conda-forge
zipp                      3.16.2             pyhd8ed1ab_0    conda-forge
zlib                      1.2.13               hd590300_5    conda-forge
zstd                      1.5.5                hfc55251_0    conda-forge
```

</details>

Cartopy: Delete Gridliner Object (not hide, actually remove) for making multiple plots
### Description

<!-- Please provide a general introduction to the issue/proposal. -->
** This was answered on Stack Overflow already **
I am trying to plot source and receiver points on a map in cartopy, where I zoom into the map based on the locations of the source and receiver. For each combination of source and receiver, I have a new map, with a new extent. I would like to find a way where I can download the map image once, and then just change the extent each time so I don't have to load in the map image every time (I have to make thousands of these). All of the events take place in one country, so I am hoping to just download the map of the whole country and then just change the extent for each loop through.

I have actually partially solved this problem, but I ran into an issue with the grid. Initially, I first set the extent to the whole country, loaded in the image, and then saved it. Then I could reset the extent for each source receiver pair, plot the two points, and then save the image. Afterwards, I just needed to erase each of the two points, and then I could set the extent another time.

However, once I added in the grid with latitude and longitude labels, I ran into an issue. I can't erase the grid and labels after each iteration, so they end up just layering on top of eachother, and the labels start to move all over the figure. The only way I can get rid of the grid is by clearing the axis, but that erases the map image.

My question: is there a way to just erase a gridliner object (not hide the labels and grid but actually delete)?

I have uploaded two of the images of the plots here, and you can see the problem in the second one.  The first image is the first plot in the loop, and each iteration adds another gridliner on top of the previous one. The second image is the last image in the loop. I can't figure out how to erase the grid, and clearing the axis deletes the map image.
 
![image](https://user-images.githubusercontent.com/56841461/93218042-c181e980-f737-11ea-8fbf-4ebe77b88087.png)
![image](https://user-images.githubusercontent.com/56841461/93218062-ca72bb00-f737-11ea-8ac1-34d32ef579f5.png)


<!--
This was answered for me on StackOverflow
-->

#### Code to reproduce

```
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io.img_tiles import Stamen

whole_extent = [18,42,8,36]
tiler = Stamen('terrain-background')

fig = plt.figure(figsize=(13.75,10))
ax1 = plt.axes(projection=ccrs.PlateCarree())
ax1.set_extent(whole_extent, crs=ccrs.PlateCarree())
ax1.add_image(tiler,6)
#Need to save initial figure to lock in initial picture, otherwise it locks in the extent from the first loop and any map that goes outside the extent of the first loop is white space
plt.savefig('plots/001_WholeFigure.png')


eventlist=[['A',22,15,30,30],['B',30,15,30,18],['C',38,24,21,15],['D',25,12,28,16],['E',38,32,21,11]]

for i in eventlist:
    eventname = i[0]
    slon = i[1] #source lon
    slat = i[2] #source lat
    lon = i[3] #receiver lon
    lat = i[4] #receiver lat

    print(f'{eventname} in progress')
    
    # Sets the zoomed in extent based on source/receiver locations
    if lon > slon:
        lonmin = slon - 2
        lonmax = lon + 2
    else:
        lonmin = lon - 2
        lonmax = slon + 2

    if lat > slat:
        latmin = slat -2
        latmax = lat + 2
    else:
        latmin = lat - 2
        latmax = slat + 2

    zoomextent = [lonmin,lonmax,latmin,latmax]


    # MAP
    ax1.set_extent(zoomextent, crs=ccrs.PlateCarree())
    receiverloc = ax1.plot(lon,lat,'r*',label='Receiver')
    sourceloc = ax1.plot(slon,slat,'k^',label='Source')
    text = ax1.text(slon+0.1,slat+0.1,eventname)
    legend = ax1.legend(loc="upper right")
    
    gl = ax1.gridlines(crs=ccrs.PlateCarree(),draw_labels=True,
        linewidth=2,color='gray',alpha=0.5,linestyle='--')
    gl.bottom_labels = gl.right_labels = False

    plt.savefig(f'plots/{eventname}.png')

    # Delete the two markers and the text so they don't show up on next loop
    receiverloc.pop(0).remove()
    sourceloc.pop(0).remove()
    text.remove()
```


Adding this to the end of the code fixed the problem

```
# Remove all artists created by the gridliner
for artist in (gl.xline_artists + gl.yline_artists +
               gl.bottom_label_artists + gl.top_label_artists +
               gl.left_label_artists + gl.right_label_artists):
    artist.remove()

# Remove the created gridliner from the list
ax1._gridliners.remove(gl)

# Try to re-connect to the draw event, which since it's already
# connected will return the existing connection id
cid = gl.axes.figure.canvas.mpl_connect('draw_event', gl._draw_event)

# Disconnect using that cid
gl.axes.figure.canvas.mpl_disconnect(cid)

```


### Operating system
Linux Mint 18.3 Ubuntu

### Cartopy version
cartopy 0.18.0




Discussion:
I think the problem is here:

https://github.com/SciTools/cartopy/blob/60c8c20b4f1c481468acc6058299fba440020ed0/lib/cartopy/mpl/geoaxes.py#L490-L491

This method is called within `GeoAxes.get_tightbbox`.  It removes all the labels and replaces them with new ones.  `Figure.get_tightbbox` [loops through all its artists and calls `get_tightbbox` on each of them](https://github.com/matplotlib/matplotlib/blob/04e13324a64b316b2b0d71b21efdab85b4e9ca6e/lib/matplotlib/figure.py#L1717-L1718), starting with the `GeoAxes`.  So, after it found the axes' bbox, `Figure.get_tightbbox` is looping through the labels that were removed.

So one way to fix this would be to not remove and re-create all the labels, as suggested at https://github.com/SciTools/cartopy/issues/2247#issuecomment-1730712335.


Resolving patch:
diff --git a/lib/cartopy/mpl/geoaxes.py b/lib/cartopy/mpl/geoaxes.py
--- a/lib/cartopy/mpl/geoaxes.py
+++ b/lib/cartopy/mpl/geoaxes.py
@@ -410,7 +410,6 @@ def __init__(self, *args, **kwargs):
         self.projection = projection
 
         super().__init__(*args, **kwargs)
-        self._gridliners = []
         self.img_factories = []
         self._done_img_factory = False
 
@@ -482,21 +481,19 @@ def _draw_preprocess(self, renderer):
         if self.get_autoscale_on() and self.ignore_existing_data_limits:
             self.autoscale_view()
 
-        # Adjust location of background patch so that new gridlines below are
-        # clipped correctly.
+        # Adjust location of background patch so that new gridlines generated
+        # by `draw` or `get_tightbbox` are clipped correctly.
         self.patch._adjust_location()
 
         self.apply_aspect()
-        for gl in self._gridliners:
-            gl._draw_gridliner(renderer=renderer)
 
     def get_tightbbox(self, renderer, *args, **kwargs):
         """
         Extend the standard behaviour of
         :func:`matplotlib.axes.Axes.get_tightbbox`.
 
-        Adjust the axes aspect ratio, background patch location, and add
-        gridliners before calculating the tight bounding box.
+        Adjust the axes aspect ratio and background patch location before
+        calculating the tight bounding box.
         """
         # Shared processing steps
         self._draw_preprocess(renderer)
@@ -508,9 +505,8 @@ def draw(self, renderer=None, **kwargs):
         """
         Extend the standard behaviour of :func:`matplotlib.axes.Axes.draw`.
 
-        Draw grid lines and image factory results before invoking standard
-        Matplotlib drawing. A global range is used if no limits have yet
-        been set.
+        Draw image factory results before invoking standard Matplotlib drawing.
+        A global range is used if no limits have yet been set.
         """
         # Shared processing steps
         self._draw_preprocess(renderer)
@@ -532,21 +528,22 @@ def draw(self, renderer=None, **kwargs):
 
     def _update_title_position(self, renderer):
         super()._update_title_position(renderer)
-        if not self._gridliners:
-            return
 
         if self._autotitlepos is not None and not self._autotitlepos:
             return
 
+        from cartopy.mpl.gridliner import Gridliner
+        gridliners = [a for a in self.artists if isinstance(a, Gridliner)]
+        if not gridliners:
+            return
+
         # Get the max ymax of all top labels
         top = -1
-        for gl in self._gridliners:
+        for gl in gridliners:
             if gl.has_labels():
+                # Both top and geo labels can appear at the top of the axes
                 for label in (gl.top_label_artists +
-                              gl.left_label_artists +
-                              gl.right_label_artists):
-                    # we skip bottom labels because they are usually
-                    # not at the top
+                              gl.geo_label_artists):
                     bb = label.get_tightbbox(renderer)
                     top = max(top, bb.ymax)
         if top < 0:
@@ -1512,7 +1509,7 @@ def gridlines(self, crs=None, draw_labels=False,
             labels_bbox_style=labels_bbox_style,
             xpadding=xpadding, ypadding=ypadding, offset_angle=offset_angle,
             auto_update=auto_update, formatter_kwargs=formatter_kwargs)
-        self._gridliners.append(gl)
+        self.add_artist(gl)
         return gl
 
     def _gen_axes_patch(self):
diff --git a/lib/cartopy/mpl/gridliner.py b/lib/cartopy/mpl/gridliner.py
--- a/lib/cartopy/mpl/gridliner.py
+++ b/lib/cartopy/mpl/gridliner.py
@@ -9,7 +9,9 @@
 import warnings
 
 import matplotlib
+import matplotlib.artist
 import matplotlib.collections as mcollections
+import matplotlib.text
 import matplotlib.ticker as mticker
 import matplotlib.transforms as mtrans
 import numpy as np
@@ -101,11 +103,7 @@ def _north_south_formatted(latitude, num_format='g'):
                                            _north_south_formatted(v))
 
 
-class Gridliner:
-    # NOTE: In future, one of these objects will be add-able to a GeoAxes (and
-    # maybe even a plain old mpl axes) and it will call the "_draw_gridliner"
-    # method on draw. This will enable automatic gridline resolution
-    # determination on zoom/pan.
+class Gridliner(matplotlib.artist.Artist):
     def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                  ylocator=None, collection_kwargs=None,
                  xformatter=None, yformatter=None, dms=False,
@@ -115,7 +113,7 @@ def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                  xpadding=5, ypadding=5, offset_angle=25,
                  auto_update=False, formatter_kwargs=None):
         """
-        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
+        Artist used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
         to add gridlines and tick labels to a map.
 
         Parameters
@@ -234,7 +232,13 @@ def __init__(self, axes, crs, draw_labels=False, xlocator=None,
         used for the map, meridians and parallels can cross both the X axis and
         the Y axis.
         """
-        self.axes = axes
+        super().__init__()
+
+        # We do not want the labels clipped to axes.
+        self.set_clip_on(False)
+        # Backcompat: the LineCollection was previously added directly to the
+        # axes, having a default zorder of 2.
+        self.set_zorder(2)
 
         #: The :class:`~matplotlib.ticker.Locator` to use for the x
         #: gridlines and labels.
@@ -332,10 +336,10 @@ def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                 raise ValueError(f"Invalid draw_labels argument: {value}")
 
         if auto_inline:
-            if isinstance(self.axes.projection, _X_INLINE_PROJS):
+            if isinstance(axes.projection, _X_INLINE_PROJS):
                 self.x_inline = True
                 self.y_inline = False
-            elif isinstance(self.axes.projection, _POLAR_PROJS):
+            elif isinstance(axes.projection, _POLAR_PROJS):
                 self.x_inline = False
                 self.y_inline = True
             else:
@@ -399,7 +403,7 @@ def __init__(self, axes, crs, draw_labels=False, xlocator=None,
         #: Control the rotation of labels.
         if rotate_labels is None:
             rotate_labels = (
-                self.axes.projection.__class__ in _ROTATE_LABEL_PROJS)
+                axes.projection.__class__ in _ROTATE_LABEL_PROJS)
         if not isinstance(rotate_labels, (bool, float, int)):
             raise ValueError("Invalid rotate_labels argument")
         self.rotate_labels = rotate_labels
@@ -436,10 +440,6 @@ def __init__(self, axes, crs, draw_labels=False, xlocator=None,
         self._drawn = False
         self._auto_update = auto_update
 
-        # Check visibility of labels at each draw event
-        # (or once drawn, only at resize event ?)
-        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)
-
     @property
     def xlabels_top(self):
         warnings.warn('The .xlabels_top attribute is deprecated. Please '
@@ -488,9 +488,6 @@ def ylabels_right(self, value):
                       'use .right_labels to toggle visibility instead.')
         self.right_labels = value
 
-    def _draw_event(self, event):
-        self._draw_gridliner(renderer=event.renderer)
-
     def has_labels(self):
         return len(self._labels) != 0
 
@@ -629,13 +626,9 @@ def _draw_gridliner(self, nx=None, ny=None, renderer=None):
             return
         self._drawn = True
 
-        # Clear lists of artists
-        for lines in [*self.xline_artists, *self.yline_artists]:
-            lines.remove()
+        # Clear lists of child artists
         self.xline_artists.clear()
         self.yline_artists.clear()
-        for label in self._labels:
-            label.artist.remove()
         self._labels.clear()
 
         # Inits
@@ -673,6 +666,7 @@ def _draw_gridliner(self, nx=None, ny=None, renderer=None):
         if not any(x in collection_kwargs for x in ['lw', 'linewidth']):
             collection_kwargs.setdefault('linewidth',
                                          matplotlib.rcParams['grid.linewidth'])
+        collection_kwargs.setdefault('clip_path', self.axes.patch)
 
         # Meridians
         lat_min, lat_max = lat_lim
@@ -696,7 +690,6 @@ def _draw_gridliner(self, nx=None, ny=None, renderer=None):
             lon_lc = mcollections.LineCollection(lon_lines,
                                                  **collection_kwargs)
             self.xline_artists.append(lon_lc)
-            self.axes.add_collection(lon_lc, autolim=False)
 
         # Parallels
         lon_min, lon_max = lon_lim
@@ -711,7 +704,6 @@ def _draw_gridliner(self, nx=None, ny=None, renderer=None):
             lat_lc = mcollections.LineCollection(lat_lines,
                                                  **collection_kwargs)
             self.yline_artists.append(lat_lc)
-            self.axes.add_collection(lat_lc, autolim=False)
 
         #################
         # Label drawing #
@@ -925,7 +917,9 @@ def update_artist(artist, renderer):
 
                     # Add text to the plot
                     text = formatter(tick_value)
-                    artist = self.axes.text(x, y, text, **kw)
+                    artist = matplotlib.text.Text(x, y, text, **kw)
+                    artist.set_figure(self.axes.figure)
+                    artist.axes = self.axes
 
                     # Update loc from spine overlapping now that we have a bbox
                     # of the label.
@@ -1239,6 +1233,26 @@ def _axes_domain(self, nx=None, ny=None):
 
         return lon_range, lat_range
 
+    def get_visible_children(self):
+        r"""Return a list of the visible child `.Artist`\s."""
+        all_children = (self.xline_artists + self.yline_artists
+                        + self.label_artists)
+        return [c for c in all_children if c.get_visible()]
+
+    def get_tightbbox(self, renderer=None):
+        self._draw_gridliner(renderer=renderer)
+        bboxes = [c.get_tightbbox(renderer=renderer)
+                  for c in self.get_visible_children()]
+        if bboxes:
+            return mtrans.Bbox.union(bboxes)
+        else:
+            return mtrans.Bbox.null()
+
+    def draw(self, renderer=None):
+        self._draw_gridliner(renderer=renderer)
+        for c in self.get_visible_children():
+            c.draw(renderer=renderer)
+
 
 class Label:
     """Helper class to manage the attributes for a single label"""


Test patch:
diff --git a/lib/cartopy/tests/mpl/baseline_images/mpl/test_gridliner/gridliner_labels_title_adjust.png b/lib/cartopy/tests/mpl/baseline_images/mpl/test_gridliner/gridliner_labels_title_adjust.png
new file mode 100644
Binary files /dev/null and b/lib/cartopy/tests/mpl/baseline_images/mpl/test_gridliner/gridliner_labels_title_adjust.png differ
diff --git a/lib/cartopy/tests/mpl/conftest.py b/lib/cartopy/tests/mpl/conftest.py
--- a/lib/cartopy/tests/mpl/conftest.py
+++ b/lib/cartopy/tests/mpl/conftest.py
@@ -35,5 +35,6 @@ def pytest_itemcollected(item):
             return
         elif path.basename == 'tests':
             subdir = item.fspath.relto(path)[:-len(item.fspath.ext)]
-            mpl_marker.kwargs['baseline_dir'] = f'baseline_images/{subdir}'
+            mpl_marker.kwargs.setdefault('baseline_dir',
+                                         f'baseline_images/{subdir}')
             break
diff --git a/lib/cartopy/tests/mpl/test_gridliner.py b/lib/cartopy/tests/mpl/test_gridliner.py
--- a/lib/cartopy/tests/mpl/test_gridliner.py
+++ b/lib/cartopy/tests/mpl/test_gridliner.py
@@ -4,6 +4,9 @@
 # See COPYING and COPYING.LESSER in the root of the repository for full
 # licensing details.
 
+import io
+from unittest import mock
+
 import matplotlib.pyplot as plt
 import matplotlib.ticker as mticker
 import numpy as np
@@ -13,7 +16,8 @@
 import cartopy.crs as ccrs
 from cartopy.mpl.geoaxes import GeoAxes
 from cartopy.mpl.gridliner import (LATITUDE_FORMATTER, LONGITUDE_FORMATTER,
-                                   classic_formatter, classic_locator)
+                                   Gridliner, classic_formatter,
+                                   classic_locator)
 from cartopy.mpl.ticker import LongitudeFormatter, LongitudeLocator
 
 
@@ -241,9 +245,14 @@ def test_grid_labels_tight():
     fig.tight_layout()
 
     # Ensure gridliners were drawn
+    num_gridliners_drawn = 0
     for ax in fig.axes:
-        for gl in ax._gridliners:
-            assert hasattr(gl, '_drawn') and gl._drawn
+        for artist in ax.artists:
+            if isinstance(artist, Gridliner) and getattr(artist, '_drawn',
+                                                         False):
+                num_gridliners_drawn += 1
+
+    assert num_gridliners_drawn == 4
 
     return fig
 
@@ -432,3 +441,82 @@ def test_gridliner_formatter_kwargs():
     fig.canvas.draw()
     labels = [a.get_text() for a in gl.bottom_label_artists if a.get_visible()]
     assert labels == ['75°O', '70°O', '65°O', '60°O', '55°O', '50°O', '45°O']
+
+
+def test_gridliner_count_draws():
+    fig = plt.figure()
+    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
+    ax.set_global()
+    gl = ax.gridlines()
+
+    with mock.patch.object(gl, '_draw_gridliner', return_value=None) as mocked:
+        ax.get_tightbbox(renderer=None)
+        mocked.assert_called_once()
+
+    with mock.patch.object(gl, '_draw_gridliner', return_value=None) as mocked:
+        fig.draw_without_rendering()
+        mocked.assert_called_once()
+
+
+@pytest.mark.mpl_image_compare(
+    baseline_dir='baseline_images/mpl/test_mpl_integration',
+    filename='simple_global.png')
+def test_gridliner_remove():
+    fig = plt.figure()
+    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
+    ax.set_global()
+    ax.coastlines()
+    gl = ax.gridlines(draw_labels=True)
+    fig.draw_without_rendering()  # Generate child artists
+    gl.remove()
+
+    assert gl not in ax.artists
+    assert not ax.collections
+
+    return fig
+
+
+def test_gridliner_save_tight_bbox():
+    # Smoke test for save with auto_update=True and bbox_inches=Tight (gh2246).
+    fig = plt.figure()
+    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
+    ax.set_global()
+    ax.gridlines(draw_labels=True, auto_update=True)
+    fig.savefig(io.BytesIO(), bbox_inches='tight')
+
+
+@pytest.mark.mpl_image_compare(filename='gridliner_labels_title_adjust.png',
+                               tolerance=grid_label_tol)
+def test_gridliner_title_adjust():
+    # Test that title do not overlap labels
+    projs = [ccrs.Mercator(), ccrs.AlbersEqualArea(), ccrs.LambertConformal(),
+             ccrs.Orthographic()]
+
+    # Turn on automatic title placement (this is default in mpl rcParams but
+    # not in these tests).
+    plt.rcParams['axes.titley'] = None
+
+    fig = plt.figure(layout='constrained')
+    fig.get_layout_engine().set(h_pad=1/8)
+    for n, proj in enumerate(projs, 1):
+        ax = fig.add_subplot(2, 2, n, projection=proj)
+        ax.coastlines()
+        ax.gridlines(draw_labels=True)
+        ax.set_title(proj.__class__.__name__)
+
+    return fig
+
+
+def test_gridliner_title_noadjust():
+    fig = plt.figure()
+    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
+    ax.set_global()
+    ax.set_title('foo')
+    ax.gridlines(draw_labels=['left', 'right'], ylocs=[-60, 0, 60])
+    fig.draw_without_rendering()
+    pos = ax.title.get_position()
+
+    # Title position shouldn't change when a label is on the top boundary.
+    ax.set_extent([-180, 180, -60, 60])
+    fig.draw_without_rendering()
+    assert ax.title.get_position() == pos