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

问题描述 投票:0回答:1

设置set_aspect('equal', adjustable='datalim')时,实际绘图范围会被调整,并且比我最初设置的范围稍宽-这是预期的。但是,当我尝试获得这些调整的边界时,get_extent()仅返回我用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

enter image description here

Obvioulsy,EXT和ext2相同。最奇怪的是,在我运行上面的代码后,get_extent()实际上将为我提供更新的值。

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

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

怎么了?

python-3.x cartopy extent
1个回答
1
投票

您发现的内容没有问题。设置范围时,您将声明与要绘制的范围相关联的值,并且只有在处理并渲染地图后,这些值才会应用。因此,当您要求当前范围(使用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()

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.