使用cartopy和AxesGrid

时间:2018-01-04 04:26:20

标签: python matplotlib cartopy

(从this Github issue复制)

我正在尝试使用cartopy docs here中显示的示例修改使用cartopy + AxesGrid的Axes的ticklabel。但是与示例不同,我只想要一个“L”形状的ticklabels,即最左边一列的垂直刻度标签和底行的水平刻度标签。

当我编辑任何斧头的水平刻度标签时,该列中所有轴的水平刻度标签随之改变。同样对于垂直刻度标签和该行中的所有轴。 (这是带有或不带有折叠的AxesGrid,但在后一种情况下我可以设置label_mode ='L'而不必费心手动更改它们。)

我在this gist创建了一个MWE,在此转载:

import cartopy.crs as ccrs
from cartopy.mpl.geoaxes import GeoAxes
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import AxesGrid

fig = plt.figure()
projection = ccrs.PlateCarree()
axes_class = (GeoAxes,
              dict(map_projection=projection))

axgrid = AxesGrid(fig, 111, axes_class=axes_class,
                  nrows_ncols=(2, 2), 
                  axes_pad=0.3,
                  label_mode='')

for n, ax in enumerate(axgrid):
    ax.set_xticks(np.linspace(-180, 180, 5), crs=projection)
    ax.set_yticks(np.linspace(-90, 90, 5), crs=projection)

# Removing the xticklabels from the upper right corner panel
# also removes them from the lower right corner panel
axgrid[1].set_xticklabels([])

1 个答案:

答案 0 :(得分:2)

@spencerkclark提供了一个解决方案,感谢this gist,并在此处转载。

fig = plt.figure()
projection = ccrs.PlateCarree()
axes_class = (GeoAxes,
              dict(map_projection=projection))

axgrid = AxesGrid(fig, 111, axes_class=axes_class,
                  nrows_ncols=(2, 2), 
                  axes_pad=0.3,
                  label_mode='')

for n, ax in enumerate(axgrid):
    ax.set_xlim(-180, 180)
    ax.set_ylim(-90, 90)
    ax.set_xticks(np.linspace(-180, 180, 5), crs=projection)
    ax.set_yticks(np.linspace(-90, 90, 5), crs=projection)


# Make ticklabels on inner axes invisible
axes = np.reshape(axgrid, axgrid.get_geometry())
for ax in axes[:-1, :].flatten():
    ax.xaxis.set_tick_params(which='both', 
                             labelbottom=False, labeltop=False)

for ax in axes[:, 1:].flatten():
    ax.yaxis.set_tick_params(which='both', 
                             labelbottom=False, labeltop=False)

编辑:如果面板数小于nrows * ncols,则此逻辑失败,例如如果它是4x2网格但只有7个面板。以下适用于这些案例:

def _hide_inner_ax_ticklabels(axgrid):
     """Produce 'L' shaped ticklabels: left row and bottom column only.

    Must do this manually when using axgrid + cartopy due to bug.
    See https://github.com/SciTools/cartopy/issues/939.
    """
    total_panels = axgrid._nrows * axgrid._ncols
    blank_panels = total_panels - axgrid.ngrids
    newgrid = np.concatenate([axgrid, [None]*blank_panels])
    axes = np.reshape(newgrid, axgrid.get_geometry())
    for ax in axes[:-1, :].flatten():
        try:
            ax.xaxis.set_tick_params(which='both', labelbottom=False, 
                                     labeltop=False)
        except AttributeError:
            pass

    for ax in axes[:, 1:].flatten():
        try:
            ax.yaxis.set_tick_params(which='both', labelbottom=False, 
                                     labeltop=False)
        except AttributeError:
            pass