0

当设置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

在此处输入图像描述

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)

怎么了 ?

4

1 回答 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()

输出:

在此处输入图像描述

于 2019-09-28T15:58:18.677 回答