Search code examples
pythonmapscartopy

Make straight lines in frames in cartopy in python


I want to create a map and frame:

import matplotlib.colors
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

fig, ax1 = plt.subplots(1, 1,subplot_kw={'projection': ccrs.Mercator()}, figsize=(7,7), gridspec_kw={'wspace': 0.2, 'hspace': 0.2})
ax1.set_extent([-50.0, 45.0, 30.0, 70.0])
ax1.coastlines('50m', color='black')
ax1.plot([-19, 40, 40, -19, -19], [35, 35, 73, 73, 35],
         color='blue', linewidth=2.5,
         transform=ccrs.Geodetic())

But the ouput is enter image description here

If I use PlateCarree:

fig, ax1 = plt.subplots(1, 1,subplot_kw={'projection': ccrs.PlateCarree()}, figsize=(7,7), gridspec_kw={'wspace': 0.2, 'hspace': 0.2})
ax1.set_extent([-50.0, 45.0, 30.0, 70.0])
ax1.coastlines('50m', color='black')
ax1.plot([-19, 40, 40, -19, -19], [35, 35, 73, 73, 35],
         color='blue', linewidth=2.5, label='Z500')

then the map is not correct: enter image description here


Solution

  • The default threshold value is too large. You must set it smaller to get more smooth curve.

    import matplotlib.colors
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    
    use_proj = ccrs.Mercator()
    use_proj._threshold /= 20.
    
    fig, ax1 = plt.subplots(1, 1,subplot_kw={'projection': use_proj}, figsize=(7,7), gridspec_kw={'wspace': 0.2, 'hspace': 0.2})
    ax1.set_extent([-50.0, 45.0, 30.0, 70.0])
    ax1.coastlines('50m', color='black')
    ax1.plot([-19, 40, 40, -19, -19], [35, 35, 73, 73, 35],
             color='blue', linewidth=2.5,
             transform=ccrs.Geodetic())
    

    merc

    See other examples here

    Edit Replace the snippet code

    transform=ccrs.Geodetic()
    

    with

    transform=ccrs.PlateCarree()
    

    after rerun, the output will be

    merc2