get_extent 在 Cartopy 中 set_aspect 设置为相等后不返回更新范围

get_extent not returning updated extent after set_aspect is set to equal in Cartopy

当设置 set_aspect('equal', adjustable='datalim') 时,我的情节的实际范围得到了调整,比我最初设置的范围略宽 - 这是预期的。
然而,当我试图获得这些调整后的边界时,get_extent() 仅 returns 我用 set_extent() 输入的内容。

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cpf
import shapely.geometry as sgeom

EXT = (9000000, 13500000, -450000, 3500000)

def to_bounds(extent):
    xmin, a, b, ymax = extent
    return xmin, b, a, ymax

platecarree = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84'))

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 1, 1, projection=platecarree)

ax.set_extent(EXT, crs=platecarree) # setting extent
ax.set_aspect('equal', adjustable='datalim', anchor='C')
ext2 = ax.get_extent() # trying to get the updated extent

ax.add_feature(cpf.LAND, facecolor='#bababa')
ax.add_feature(cpf.BORDERS, edgecolor='white')
ax.add_geometries([sgeom.box(*to_bounds(EXT))], crs=platecarree, facecolor='none', edgecolor='yellow', linewidth=3)     # initial extent
ax.add_geometries([sgeom.box(*to_bounds(ext2))], crs=platecarree, facecolor='none', edgecolor='indianred', linewidth=1) # updated extent

很明显,EXT 和 ext2 是一样的。
最奇怪的是,在我 运行 上面的代码之后,get_extent() 实际上会给我更新的值。

ext2 # (9000000.0, 13499999.999999998, -449999.99999999994, 3500000.0)

ax.get_extent() # (8546909.492273731, 13953090.507726269, -449999.99999999994, 3500000.0)

怎么了?

您的发现没有问题。设置范围时,您声明了与要绘制的范围关联的值,并且在处理和渲染地图之前不会应用它们。因此,当您询问当前范围(使用 ax.get_extent())时,您不会获得刚刚设置的值。要获得您期望的结果,您必须 运行 plt.draw()。这是修改后的代码和描述该过程的输出:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cpf
import shapely.geometry as sgeom

EXT = (9000000, 13500000, -450000, 3500000)

def to_bounds(extent):
    xmin, a, b, ymax = extent
    return xmin, b, a, ymax

platecarree = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84'))

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 1, 1, projection=platecarree)

ax.set_extent(EXT, crs=platecarree) # setting extent
print("1. ax.set_extent(EXT..):", ax.get_extent())  # after EXT is used

ax.set_aspect('equal', adjustable='datalim', anchor='C')  # the extent changes at this step

ext2 = ax.get_extent()    # trying to get the updated extent; fails here!
print("2. ext2:", ext2 )  # print check; extent is not updated yet!

plt.draw()  # this updates the extent
print("3. ax.get_extent():", ax.get_extent())  # expected to have other values; OK now

ax.add_feature(cpf.LAND, facecolor='#bababa')
ax.add_feature(cpf.BORDERS, edgecolor='white')
ax.add_geometries([sgeom.box(*to_bounds(EXT))], crs=platecarree, facecolor='none', edgecolor='yellow', linewidth=4)     # initial extent
ax.add_geometries([sgeom.box(*to_bounds(ax.get_extent()))], crs=platecarree, facecolor='none', edgecolor='indianred', linewidth=5) # updated extent

plt.show()

输出: