MPL Basemap投影输出异常求助:无地球背景图
Basemap绘制Mollweide投影无背景图(空白输出)问题解决
问题详情
使用以下代码调用Basemap的shadedrelief方法绘制Mollweide投影时,仅得到空白输出(无地球背景图),bluemarble等其他背景图方法也存在同样问题。
实际输出:
预期输出:
代码示例:
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from itertools import chain def draw_map(m, scale=0.2): # draw a shaded-relief image im1 = m.shadedrelief(scale=scale) # lats and longs are returned as a dictionary lats = m.drawparallels(np.linspace(-90, 90, 13)) lons = m.drawmeridians(np.linspace(-180, 180, 13)) # keys contain the plt.Line2D instances lat_lines = chain(*(tup[1][0] for tup in lats.items())) lon_lines = chain(*(tup[1][0] for tup in lons.items())) all_lines = chain(lat_lines, lon_lines) # cycle through these lines and set the desired style for line in all_lines: line.set(linestyle='-', alpha=0.3, color='w') fig = plt.figure(figsize=(8, 6), edgecolor='w') m = Basemap(projection='moll', resolution=None, lat_0=0, lon_0=0) draw_map(m)
问题在Python 3.11.0环境下的VS Code Jupyter Notebook、Google Colab及独立Python文件中均能复现。
问题原因
Basemap是已停止维护的老旧地理可视化库,对Python 3.10及以上版本的兼容性极差。其背景图相关的下载、渲染逻辑依赖的底层网络请求、文件处理机制在新版本Python中已失效,且官方不会再发布修复补丁。
解决方案
方案1:降级Python版本
将Python版本降级到3.9或更低,Basemap在这些版本中可以正常运行,直接执行原代码即可生成预期的背景图。
方案2:替换为现代库Cartopy(推荐)
Basemap已被Matplotlib官方弃用,推荐使用Cartopy作为替代,以下是实现等价功能的代码:
import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.feature import ShadedRelief fig = plt.figure(figsize=(8, 6), edgecolor='w') # 设置Mollweide投影 ax = plt.axes(projection=ccrs.Mollweide()) # 添加晕渲地貌背景 ax.add_feature(ShadedRelief(scale=0.2)) # 绘制经纬线(样式与原代码对齐) ax.gridlines(draw_labels=False, linestyle='-', alpha=0.3, color='white') plt.show()
如果需要类似bluemarble的高清背景图效果,可替换背景加载逻辑为:
from cartopy.feature import NaturalEarthFeature # 添加蓝大理石风格背景 ax.add_feature(NaturalEarthFeature('raster', 'NE1_HR_LC_SR_W_DR', '10m'))
Cartopy支持Python 3.10+版本,且持续维护,功能覆盖Basemap的所有场景,同时提供更灵活的扩展能力。
内容的提问来源于stack exchange,提问作者Ghost Ops
相关产品推荐
相关产品推荐

