在Cartopy中指定纬度/经度标签位置在某些侧面移除

问题描述

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标签,在顶部放置无标签。使用标记列表可以轻松地在底图中完成此操作。我想知道现在用cartopy是否可行。 几次失败的尝试:

  1. 我遇到了Github open issue for cartopy on a similar topic,但建议的方法不适用于这种情况。添加gl.ylocator = mticker.FixedLocator(yticks)不会执行任何操作,添加gl.xlocator = mticker.FixedLocator(xticks)会消除大多数lon标签,除了左右两侧的180行,但其他所有lon标签都丢失了。 80N纬度标签仍位于顶部see here上。在更仔细地阅读了该线程之后,对于将来的cartopy发行版,似乎仍在继续努力。
  2. 使用gl.top_labels=False也不起作用。
  3. y_inline设置为True会使lat标签完全消失。我想这可能是因为我使用了轴范围。纬度标签可能在盒子外面的某些经线上。这是一个单独的问题,关于如何指定内联标签的经度线/位置。

现在,我选择关闭标签。任何建议和临时解决方案将不胜感激。此时,上面的示例等地图可用于快速查看,但尚未准备好用于任何正式用途。

更新: 根据@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。因此,我需要进行一些更简单的调整才能将其放回原处。

解决方法

在找到更好的解决方案之前,这可能是您项目的解决方法。

# more code above this line

# this suppresses drawing labels on top edges
# only longitude_labels disappear,some latitude_labels persist
gl.top_labels=False

# workaround here to manipulate the remaining labels
plt.draw()  #enable the use of ._lables()
for ea in gl._labels:
    #here,ea[2] is a Text object
    #print(ea)
    if '80°N'==ea[2].get_text():
        # set it a blank string
        ea[2].set_text("")

ax.set_title("No Labels on Top Edge");
plt.show()

输出图:

outputplot

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...