[Python] How to easily add a sub_axes with proper position and size in matplotlib and cartopy?

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    I want to add a 2nd axes at the top right corner of a 1st axes. After googling, I found two ways to do things like this: fig.add_axes(), and mpl_toolkits.axes_grid.inset_locator.inset_axes. But the fig.add_axes() doesn't accept transform arg. So the following code throws an error. So the position can't be under the parent axes coordinates but the figure coordinates.

    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    fig, ax = plt.subplots(1, 1, subplot_kw={'projection': ccrs.PlateCarree()})
    ax2 = fig.add_axes([0.8, 0, 0.2, 0.2], transform=ax.transAxes, projection=ccrs.PlateCarree())


    And inset_axes() doesn't accept the projection arg, so I can't add ax2 as a cartopy geo-axes.

    from mpl_toolkits.axes_grid.inset_locator import inset_axes
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    fig, ax = plt.subplots(1, 1, subplot_kw={'projection': ccrs.PlateCarree()})

    # The following line doesn't work
    ax2 = inset_axes(ax, width='20%', height='20%', axes_kwargs={'projection': ccrs.PlateCarree()})
    # Doesn't work neither:
    ax2 = inset_axes(ax, width='20%', height='20%', projection=ccrs.PlateCarree())


    I've asked the question at matplotlib issue. It seems the following code works well as long as it's not a cartopy axes.

    import matplotlib as mpl
    fig, ax = plt.subplots(1, 1)
    box = mpl.transforms.Bbox.from_bounds(0.8, 0.8, 0.2, 0.2)
    ax2 = fig.add_axes(fig.transFigure.inverted().transform_bbox(ax.transAxes.transform_bbox(box)))

    Question:


    How to easily add a sub_axes with proper position and size in matplotlib and cartopy?

    As I understand, after ax.set_extend(), the size of axes will change. So maybe is there a way that some point of sub_axes (eg: top right corner of ax2) can be anchored at one fixed position of the parent_axes (eg: top right corner of ax1)?

    Continue reading...

Compartilhe esta Página