Search code examples
pythoncartopy

how to make map lines visible over data in cartopy?


I am trying to make map lines always on top of data, but cannot find the right command/options to do so in cartopy. In the plot below, I want the thick blue line "under" the black state lines but on top of the beige states.

Code:

import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import os,sys

conus_proj = ccrs.LambertConformal(central_longitude=-96,central_latitude=39.0)
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(1,1,1,projection=conus_proj)
ax.set_extent([-120,-70,22,50])
#ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.OCEAN, facecolor='#CCFEFF')
ax.add_feature(cfeature.LAKES, facecolor='#CCFEFF')
ax.add_feature(cfeature.RIVERS, facecolor='#CCFEFF')
ax.add_feature(cfeature.LAND, facecolor='#FFE9B5')
state_borders = cfeature.NaturalEarthFeature(category='cultural', name='admin_1_states_provinces_lakes', scale='50m', facecolor='#FFE9B5')
ax.add_feature(state_borders, edgecolor='black')

plt.plot([-120,-70],[35,45],linewidth=8, transform=ccrs.PlateCarree())
plt.show()

I have tried changing the zorder of ax.add_feature(state_borders...) and plt.plot(...) but have received weird results. The state borders are on top by default with pcolormesh, but don't appear to be so with plt.plot

Here is the output of the above code: enter image description here


Solution

  • The reason things turn out differently for pcolormesh vs. plot is that those have different default zorders. If I set the zorder for the state borders (note below that I use Cartopy's built-in support for states) to 10, I get them to appear on top of the plot:

    import matplotlib.pyplot as plt
    import numpy as np
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature
    import os,sys
    
    conus_proj = ccrs.LambertConformal(central_longitude=-96,central_latitude=39.0)
    fig = plt.figure(figsize=(10,8))
    ax = fig.add_subplot(1,1,1,projection=conus_proj)
    ax.set_extent([-120,-70,22,50])
    
    ax.add_feature(cfeature.COASTLINE)
    ax.add_feature(cfeature.OCEAN, facecolor='#CCFEFF')
    ax.add_feature(cfeature.LAKES, facecolor='#CCFEFF')
    ax.add_feature(cfeature.RIVERS, edgecolor='#CCFEFF')
    ax.add_feature(cfeature.LAND, facecolor='#FFE9B5')
    ax.add_feature(cfeature.STATES, edgecolor='black', zorder=10)
    
    plt.plot([-120,-70],[35,45],linewidth=8, transform=ccrs.PlateCarree())
    plt.show()
    

    I also had to remove the face colors on some of the features.