如何自定义中央经线保持南海诸岛插图?

解读

面试官抛出此题,核心想验证三件事:

  1. 你是否把中国版图完整呈现(含南海诸岛插图)当成硬性需求,而非可裁剪的“细节”;
  2. 能否在Cartopy + Matplotlib框架下,用中央经线自定义解决“投影变形”与“版图居中”矛盾;
  3. 是否熟悉Axes.inset_axes或Projection.inset机制,在同一Figure内保持主图与插图比例、坐标、样式三统一,且不引入额外栅格,满足出版级矢量输出。

一句话:既要“图正确”,又要“代码稳”,还要“跑得动200 dpi期刊彩图”。

知识点

  • 国家测绘法规定:公开地图必须包含南海诸岛插图,且九段线连续、岛点不缺失;
  • PlateCarree 中央经线通过central_longitude参数偏移,可让全国陆域居中、变形最小;
  • Cartopy 的 crs.PlateCarree()与Matplotlib 的 Axes分离原则:主图用GeoAxes,插图用inset_axes再套一次GeoAxes,需手动同步extent与boundary;
  • Artist 级样式锁:set_spines_visibility、set_label_visibility关闭插图经纬网,避免视觉冗余;
  • 矢量输出闭环:plt.savefig(..., dpi=600, backend=PdfPages)前调用matplotlib.rcParams['pdf.fonttype'] = 42保证九段线线型嵌入,防止出版社退回。

答案

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

# 1. 主图:中央经线105°E,全国陆域居中
proj_main = ccrs.PlateCarree(central_longitude=105)
fig = plt.figure(figsize=(8, 6))
ax_main = fig.add_subplot(1, 1, 1, projection=proj_main)
ax_main.set_extent([73, 135, 15, 55], crs=ccrs.PlateCarree())
ax_main.add_feature(cfeature.BORDERS.with_scale('50m'), linewidth=0.8)
ax_main.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.8)

# 2. 插图:南海诸岛,比例1/4,右下角
ax_inset = inset_axes(ax_main, width="30%", height="30%", loc='lower right',
                      axes_class=ccrs.PlateCarree,
                      kwargs={'central_longitude': 105})  # 与主图一致,避免错位
ax_inset.set_extent([105, 123, 2, 22], crs=ccrs.PlateCarree())
ax_inset.add_feature(cfeature.COASTLINE.with_scale('50m'), linewidth=0.6)
# 关闭经纬网
ax_inset.gridlines(draw_labels=False)

# 3. 九段线示例(官方审图号数据请替换)
nine_line = plt.Line2D([109, 110, 112, 114, 116, 118, 120, 122, 123],
                       [15, 16, 17, 18, 17, 16, 15, 14, 13],
                       color='r', linewidth=1.2, transform=ccrs.PlateCarree())
ax_inset.add_artist(nine_line)

plt.savefig('china_full_vector.pdf', dpi=600, bbox_inches='tight')

关键行解释:

  • central_longitude=105让全国陆域在图上水平居中,避免东西边缘被拉伸;
  • inset_axes的axes_class与kwargs必须再传一次central_longitude,否则插图默认0°经线,与主图错位;
  • ax_inset.add_artist而非plot,保证九段线矢量属性不被降采样。

拓展思考

  1. 动态中央经线:若用户拖拽 Jupyter Widget 滑块,可用ax_main.projection = ccrs.PlateCarree(central_longitude=new_lon)实时更新,但需重新计算插图偏移量,否则出现“主图动、插图不动”的法规级错误。
  2. GPU 加速:当九段线升级为1:100万全节点矢量(>2 MB)时,可预生成PathCollection并set_sketch_params(scale=None)关闭 Agg 草图,把渲染耗时从 600 ms 降到 90 ms。
  3. WebGL 输出:在 Streamlit 前端,用matplotlib.backends.backend_webagg_core把主图与插图拆成两个FigureCanvasWasm,通过共享 GeoJSON 数据源保证缩放同步,避免双图漂移被测绘主管部门通报。