【发布时间】:2021-01-09 03:34:42
【问题描述】:
Cartopy 0.18.0 中为任何地图投影添加纬度/经度标签的新功能非常出色。这是这个包的一个很好的补充。对于某些地图,尤其是在极地地区,纬度/经度标签可能非常拥挤。这是一个例子。
from matplotlib import pyplot as plt
import numpy as np
import cartopy.crs as ccrs
pcproj = ccrs.PlateCarree()
lon0 = -150
mapproj = ccrs.LambertAzimuthalEqualArea(
central_longitude=lon0,central_latitude=75,
)
XLIM = 600e3; YLIM=700e3
dm =5; dp=2
fig = plt.figure(0,(7,7))
ax = fig.add_axes([0.1,0.1,0.85,0.9],projection=mapproj)
ax.set_extent([-XLIM,XLIM,-YLIM,YLIM],crs=mapproj)
ax.coastlines(resolution='50m',color='.5',linewidth=1.5)
lon_grid = np.arange(-180,181,dm)
lat_grid = np.arange(-80,86,dp)
gl = ax.gridlines(draw_labels=True,
xlocs=lon_grid,ylocs=lat_grid,
x_inline=False,y_inline=False,
color='k',linestyle='dotted')
gl.rotate_labels = False
这是输出图:I can't embed image yet, so here is the link
我正在寻找的是在左侧和右侧有 lat 标签,在底部有 lon 标签,顶部没有标签。这可以在 Basemap 中使用标志列表轻松完成。我想知道现在卡托皮是否可以做到这一点。 多次尝试失败:
- 我遇到了Github open issue for cartopy on a similar topic,但建议的方法不适用于这种情况。添加
gl.ylocator = mticker.FixedLocator(yticks)没有任何作用,添加gl.xlocator = mticker.FixedLocator(xticks)会删除大多数lon 标签,除了左右两侧的180 行,但所有其他lon 标签都丢失了。 80N lat 标签仍然在顶部,see here。在更仔细地阅读了该线程之后,它似乎仍在为未来的 cartopy 版本而持续努力。 - 使用
gl.top_labels=False也不起作用。 - 将
y_inline设置为True会使纬度标签完全消失。我想这可能是因为我使用了轴范围。纬度标签可能位于框外的某些经度线上。这是一个单独的问题,关于如何指定内联标签的经度线/位置。
现在,我选择关闭标签。任何建议和临时解决方案将不胜感激。此时,上述示例等地图可用于快速查看,但尚未准备好正式使用。
更新: 根据@swatchai 的建议,下面有一个临时解决方法:
# --- add _labels attribute to gl
plt.draw()
# --- tol is adjusted based on the positions of the labels relative to the borders.
tol = 20
for ea in gl._labels:
pos = ea[2].get_position()
t_label = ea[2].get_text()
# --- remove lon labels on the sides
if abs(abs(pos[0])-XLIM)<tol:
if 'W' in t_label or 'E' in t_label or '180°' in t_label:
print(t_label)
ea[2].set_text('')
# --- remove labels on top
if abs(pos[1]-YLIM)<tol:
ea[2].set_text('')
这几乎是我想要的,除了the 74N labels are missing,因为它接近侧面的 170W 标签,而 cartopy 选择了 170W 标签而不是 74N。所以我需要一些更简单的调整来把它放回原处。
【问题讨论】:
标签: python-3.x label cartopy gridlines