You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cartopy set_extent()方法报错求助:TypeError问题排查

问题描述

尝试在地图上绘制特定区域的等高线图,绘制等高线本身无问题,但设置地图范围时(无论是否绘制等高线)出现错误,使用Cartopy版本0.20.3。

错误代码

import cartopy.crs as ccrs
import matplotlib.pyplot as plt


p = ccrs.Mercator()
ax = plt.axes(projection=p)
ax.set_extent([-140, -60, 20, 70], crs=ccrs.Mercator())
ax.coastlines()
ax.gridlines()
plt.show()

报错信息

TypeError                                 Traceback (most recent call last) Input In [5], in <cell line: 7>()
      5 p = ccrs.Mercator()
      6 ax = plt.axes(projection=p)
----> 7 ax.set_extent([-140, -60, 20, 70], crs=ccrs.Mercator())
      8 ax.coastlines()
      9 ax.gridlines()
File ~\Anaconda3\envs\geospatial\lib\site-packages\cartopy\mpl\geoaxes.py:904,
in GeoAxes.set_extent(self, extents, crs)
    901         projected = boundary

    903 if projected is None:
---> 904     projected = self.projection.project_geometry(domain_in_crs, crs)
    905 try:
    906     # This might fail with an unhelpful error message ('need more
    907     # than 0 values to unpack') if the specified extents fall outside
    908     # the projection extents, so try and give a better error message.
    909     x1, y1, x2, y2 = projected.bounds

File ~\Anaconda3\envs\geospatial\lib\site-packages\cartopy\crs.py:805, in Projection.project_geometry(self, geometry, src_crs)
    803 if not method_name:
    804     raise ValueError(f'Unsupported geometry type {geom_type!r}')
---> 805 return getattr(self, method_name)(geometry, src_crs)

File ~\Anaconda3\envs\geospatial\lib\site-packages\cartopy\crs.py:811, in Projection._project_line_string(self, geometry, src_crs)
    810 def _project_line_string(self, geometry, src_crs):
---> 811     return cartopy.trace.project_linear(geometry, src_crs, self)

File lib/cartopy/trace.pyx:628, in cartopy.trace.project_linear()

File lib/cartopy/trace.pyx:100, in cartopy.trace.geos_from_shapely()

TypeError: an integer is required
解决方案

问题出在set_extent的crs参数使用错误:你传入的是ccrs.Mercator()(一个新的Mercator投影实例),但提供的范围坐标是经纬度值,应使用地理坐标系ccrs.PlateCarree()而非Mercator投影。

修改后的代码:

import cartopy.crs as ccrs
import matplotlib.pyplot as plt


p = ccrs.Mercator()
ax = plt.axes(projection=p)
# 将crs参数改为ccrs.PlateCarree(),匹配传入的经纬度范围
ax.set_extent([-140, -60, 20, 70], crs=ccrs.PlateCarree())
ax.coastlines()
ax.gridlines()
plt.show()

原理说明

set_extent的crs参数用于指定传入的extents坐标所属的坐标系。[-140, -60, 20, 70]是经度和纬度值,属于地理坐标系(PlateCarree),而非Mercator投影坐标系。错误传入Mercator投影实例会导致Cartopy在投影转换时触发类型错误。


内容的提问来源于stack exchange,提问作者Clim Sci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:54:52