Examples of how to plot a rectangle on a cartopy map with python:
Exemple 1 (PlateCarree projection)
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import cartopy.crs as ccrs
fig = figure(num=None, figsize=(12, 10), dpi=100, edgecolor='k')
proj = ccrs.PlateCarree()
ax = plt.axes(projection=proj)
ax.set_global()
long = -70.
lat = -45.
ax.add_patch(mpatches.Rectangle(xy=[long, lat], width=90, height=90,
facecolor='blue',
alpha=0.2,
transform=ccrs.PlateCarree())
)
plt.scatter( long, lat,
color='red', linewidth=2, marker='o', s=20,
transform=ccrs.PlateCarree())
ax.gridlines()
ax.coastlines()
plt.title('How to plot a transparent rectangle on a map with cartopy ?')
plt.savefig("plot_rectangle_cartopy_01.png", bbox_inches='tight', facecolor='white')
plt.show()
Exemple 2 (Robinson projection)
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import cartopy.crs as ccrs
fig = figure(num=None, figsize=(12, 10), dpi=100, edgecolor='k')
proj = ccrs.Robinson()
ax = plt.axes(projection=proj)
ax.set_global()
ax.add_patch(mpatches.Rectangle(xy=[-70, -45], width=90, height=90,
facecolor='blue',
alpha=0.2,
transform=ccrs.PlateCarree())
)
plt.scatter( -70, -45,
color='red', linewidth=2, marker='o', s=20,
transform=ccrs.PlateCarree())
ax.gridlines()
ax.coastlines()
plt.title('How to plot a transparent rectangle on a map with cartopy ?')
plt.savefig("plot_rectangle_cartopy_02.png", bbox_inches='tight', facecolor='white')
plt.show()
Exemple 3 using mpatches.Polygon
from matplotlib.pyplot import figure
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import matplotlib.patches as mpatches
fig = figure(num=None, figsize=(12, 10), dpi=100, edgecolor='k')
map_proj = ccrs.PlateCarree()
ax = plt.axes(projection=map_proj)
ax.set_global()
ax.gridlines()
ax.coastlines(linewidth=0.5, color='k', resolution='50m')
lat_corners = np.array([-45., -45., -45.+90, -45.+90])
lon_corners = np.array([ -70., -70+90., -70.+90, -70.])
poly_corners = np.zeros((len(lat_corners), 2), np.float64)
poly_corners[:,0] = lon_corners
poly_corners[:,1] = lat_corners
poly = mpatches.Polygon(poly_corners, closed=True, ec='r', fill=True, lw=1, fc=None, transform=ccrs.PlateCarree())
ax.add_patch(poly)
plt.title('How to plot a transparent rectangle on a map with cartopy ?')
plt.savefig("plot_rectangle_cartopy_03.png", bbox_inches='tight', facecolor='white')
plt.show()