Skip to content

Instantly share code, notes, and snippets.

@cpelley
Last active December 18, 2015 12:18
Show Gist options
  • Save cpelley/5781535 to your computer and use it in GitHub Desktop.
Save cpelley/5781535 to your computer and use it in GitHub Desktop.
Cartopy gridlines with labels on funky projections
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
def workaround_gridlines(src_proj, labels=True):
# Workaround for plotting lines of constant latitude/longitude as gridlines
# labels not supported for this projection.
lats = np.linspace(-90, 90, num=181, endpoint=True)
lons = np.linspace(0, 360, num=360, endpoint=False)
yn = np.zeros(len(lats))
lona = lons + yn.reshape(len(lats),1)
cs2 = plt.contour(lons, lats, lona, 10, transform=src_proj, colors='b', linestyles='dashed')
plt.clabel(cs2, fontsize=9, inline=True)
yt = np.zeros(len(lons))
lata = lats.reshape(len(lats),1) + yt
cs = plt.contour(lons, lats, lata, 10, transform=src_proj, colors='r', linestyles='dashed')
plt.clabel(cs, fontsize=9, inline=True)
def main():
trgt_proj = ccrs.Orthographic(central_latitude=-90)
src_proj = ccrs.PlateCarree()
src_crs = ccrs.Geodetic()
ax = plt.axes(projection=trgt_proj)
ax.stock_img()
ln = np.array([-179, 175])
lt = np.array([-60, -65])
# Plot gridlines
workaround_gridlines(src_proj)
ax.set_extent((ln.min(), ln.max(), lt.min(), lt.max()), crs=src_proj)
ax.coastlines(resolution='110m', color='black', linewidth=0.5, zorder=1)
plt.plot(ln, lt, '-k', transform=src_crs)
plt.scatter(x=ln, y=lt, transform=src_crs)
plt.show()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment