Cartopy:如何在绘图外侧添加坐标轴刻度标记
在Cartopy中为坐标轴添加外侧刻度标记
我编写了如下Cartopy代码,希望在坐标轴外侧添加刻度标记。找到了相关示例但难以适配到自己的代码中,理想情况下不想手动设置刻度位置,求帮助!
原始代码:
import matplotlib.pyplot as plt from cartopy.crs import Mercator, PlateCarre lon_min = -50 lon_max = 40 lat_max = 30 lat_min = -70 fontsize=8 ax = plt.axes(projection = Mercator(latitude_true_scale = (lat_min+lat_max)/2)) ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=PlateCarree()) # Make gridlines gl = ax.gridlines(draw_labels=True, x_inline=False, y_inline=False, crs=PlateCarree(), visible=True) # Only show ticks on lower and left axes gl.bottom_labels = True gl.left_labels = True gl.top_labels = False gl.right_labels = False # Adjust rotation and size of tick labels gl.xlabel_style['size']=fontsize gl.xlabel_style['rotation']=0 gl.xlabel_style['ha'] = 'center' gl.ylabel_style['size']=fontsize gl.ylabel_style['rotation']=90 gl.ylabel_style['ha'] = 'center'
当前效果:
解决方案
不需要手动指定刻度位置,结合Cartopy的gridlines和matplotlib的轴设置即可实现。核心思路是复用gridlines自动生成的刻度位置,再将刻度调整到坐标轴外侧:
修改后的代码:
import matplotlib.pyplot as plt from cartopy.crs import Mercator, PlateCarree lon_min = -50 lon_max = 40 lat_max = 30 lat_min = -70 fontsize=8 ax = plt.axes(projection = Mercator(latitude_true_scale = (lat_min+lat_max)/2)) ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=PlateCarree()) # Make gridlines gl = ax.gridlines(draw_labels=True, x_inline=False, y_inline=False, crs=PlateCarree(), visible=True) # Only show ticks on lower and left axes gl.bottom_labels = True gl.left_labels = True gl.top_labels = False gl.right_labels = False # Adjust rotation and size of tick labels gl.xlabel_style['size']=fontsize gl.xlabel_style['rotation']=0 gl.xlabel_style['ha'] = 'center' gl.ylabel_style['size']=fontsize gl.ylabel_style['rotation']=90 gl.ylabel_style['ha'] = 'center' # 获取gridlines自动计算的刻度位置 xticks = gl.xlocator()(ax.get_xlim()) yticks = gl.ylocator()(ax.get_ylim()) # 将刻度应用到坐标轴,使用PlateCarree投影确保坐标正确 ax.set_xticks(xticks, crs=PlateCarree()) ax.set_yticks(yticks, crs=PlateCarree()) # 设置刻度显示在坐标轴外侧,仅保留左下侧刻度 ax.tick_params(axis='x', direction='out', bottom=True, top=False, labelsize=fontsize) ax.tick_params(axis='y', direction='out', left=True, right=False, labelsize=fontsize)
关键说明
- 复用自动刻度:通过
gl.xlocator()和gl.ylocator()获取gridlines自动生成的经纬度刻度,避免手动输入刻度值。 - 绑定投影坐标:设置刻度时指定
crs=PlateCarree(),确保刻度位置对应正确的经纬度。 - 调整刻度位置:用
tick_params将刻度方向设为out,并只显示左下侧的刻度,和标签显示逻辑保持一致。
内容的提问来源于stack exchange,提问作者blupp
相关产品推荐
相关产品推荐

