Search code examples
pythonmatplotlibcartopymap-projections

Remove top and right spine in GeoAxesSubplot


I'm trying to remove the top and right spine of a plot, and initially tried

# Create a figure and axis with PlateCarree projection
fig, ax = plt.subplots(figsize=(11, 6), 
                       subplot_kw={'projection': ccrs.PlateCarree()})

ax.coastlines()

# Reintroduce spines
ax.spines['top'].set_visible(True)
ax.spines['right'].set_visible(True)

ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree())
ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree())

# Show the plot
plt.show()

which gives me this figure, i.e. it clearly didn't work

enter image description here

I then tried to remove the frame and add the two spines I want

# Create a figure and axis with PlateCarree projection
fig, ax = plt.subplots(figsize=(11, 6), 
                       subplot_kw={'projection': ccrs.PlateCarree(), 
                                   'frameon': False})

ax.coastlines()

# Reintroduce spines
ax.spines['left'].set_visible(True)
ax.spines['bottom'].set_visible(True)

ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree())
ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree())

# Show the plot
plt.show()

and this also doesn't quite work - I successfully remove the frame but can't reintroduce the left and bottom spine back

enter image description here

I did see this post but when I try to apply this to my code

# Create a figure and axis with PlateCarree projection
fig, ax = plt.subplots(figsize=(11, 6), 
                       subplot_kw={'projection': ccrs.PlateCarree()})

ax.coastlines()

# Reintroduce spines
ax.outline_patch.set_visible(False)
ax.spines['left'].set_visible(True)  
ax.spines['bottom'].set_visible(True)  

ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree())
ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree())

# Show the plot
plt.show()

I get the error

AttributeError: 'GeoAxes' object has no attribute 'outline_patch'

Surely there must be a way to achieve this? Does anyone know how to do this? I'm using python 3.10.


Solution

  • I think the modern equivalent of outline_patch is spines['geo']:

    # Create a figure and axis with PlateCarree projection
    fig, ax = plt.subplots(figsize=(11, 6), 
                           subplot_kw={'projection': ccrs.PlateCarree()})
    
    ax.coastlines()
    
    ax.spines['geo'].set_visible(False)
    ax.spines['left'].set_visible(True)
    ax.spines['bottom'].set_visible(True)
    
    ax.set_xticks(range(-180, 181, 30), crs=ccrs.PlateCarree())
    ax.set_yticks(range(-90, 91, 30), crs=ccrs.PlateCarree())
    
    # Show the plot
    plt.show()
    

    enter image description here