为什么在此 cartopy 投影图中添加图例会显着增加执行时间(以及如何解决此问题)?

Why does adding a legend in this cartopy projection figure significantly increase the execution time (and how can fix this)?

所以我写了一个脚本来制作可以正常工作的图形(参见下面的模型示例)。但是当我在图中添加图例时,执行时间会增加很多。我真的不明白这里发生了什么,我天真地认为简单地添加一个图例并不是一件复杂的事情。

我怀疑这与 cartopy 投影有关,因为如果我不使用它,它工作正常。

这是什么问题,我该如何避免?

有问题的代码:

import numpy as np
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Mockup dataset
num = 300
lat = np.linspace(-54,-59,num=num)
lon = np.linspace(-5,5, num=num)

data = np.outer(lat,lon)

ds = xr.DataArray(data=data,
                 dims=["lat", "lon"],
                 coords=dict(lon=lon, lat=lat))


# Map projection
map_proj = ccrs.SouthPolarStereo()

ax = plt.axes(projection=map_proj)
ax.gridlines(draw_labels=True)
ax.set_extent([-3,4,-58,-54])

# Plot image
ds.plot(cmap="gray", 
        add_colorbar=False,
        transform=ccrs.PlateCarree(), # data projection
        subplot_kws={'projection': map_proj}) # map projection

# Plot contours
cs = ds.plot.contour(transform=ccrs.PlateCarree())

# Make legend
proxy = [matplotlib.lines.Line2D([],[], c=pc.get_color()[0]) for pc in cs.collections]
labels = ["foo"] * len(cs.collections)
plt.legend(proxy, labels)

没有cartopy投影的代码:

import numpy as np
import xarray as xr
import matplotlib
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Mockup dataset
num = 300
lat = np.linspace(-54,-59,num=num)
lon = np.linspace(-5,5, num=num)

data = np.outer(lat,lon)

ds = xr.DataArray(data=data,
                 dims=["lat", "lon"],
                 coords=dict(lon=lon, lat=lat))

# Plot image
ds.plot(cmap="gray", 
        add_colorbar=False) # map projection

# Plot contours
cs = ds.plot.contour()

# Make legend
proxy = [matplotlib.lines.Line2D([],[], c=pc.get_color()[0]) for pc in cs.collections]
plt.legend(proxy, labels)

plt.legend(proxy, labels) 默认为 loc='best',如果轴中有大量数据,该算法使用的算法可能会很慢,如果数据也有复杂的转换,则速度尤其慢。而是手动执行 ax.legend(proxy, labels, loc='upper right')。参见 https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html