I'm trying to plot some data on the world map, which can be centered either near the Atlantic (i.e. 180°W–180°E) or at the Pacific (i.e. 0°–360°). Here's the program (with fictitious data):
import argparse
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
parser = argparse.ArgumentParser()
parser.add_argument('--center', choices=['atlantic', 'pacific'], default='atlantic')
parser.add_argument('--outfile', default='plot.png')
args = parser.parse_args()
lat = np.linspace(-89.95, 89.95, 1800)
if args.center == 'atlantic':
lon = np.linspace(-179.95, 179.95, 3600)
clon = 0
else:
lon = np.linspace(0.05, 359.95, 3600)
clon = 180
x, y = np.meshgrid(lon, lat)
z = np.sin(x / 180 * np.pi) * np.sin(y / 180 * np.pi)
fig = plt.figure(figsize=(21, 7))
crs = ccrs.PlateCarree(central_longitude=clon)
ax = plt.axes(projection=crs)
ax.coastlines(resolution='110m', color='white', linewidth=2)
gl = ax.gridlines(crs=crs, draw_labels=True, linewidth=1, color='black', linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 16, 'color': 'black'}
gl.ylabel_style = {'size': 16, 'color': 'black'}
plt.contourf(x, y, z, cmap='RdYlBu_r')
cb = plt.colorbar(ax=ax, orientation='vertical', pad=0.02, aspect=16, shrink=0.8)
cb.ax.tick_params(labelsize=16)
fig.savefig(args.outfile, bbox_inches='tight', pad_inches=0.1)
However, when I switch from --center=atlantic
to --center=pacific
, only the coastlines move, while the X-axis and the data do not, resulting in an inconsistent plot. (With my fictitious data, North America should be in blue and Asia should be in red.)
How can I make a correct plot that's centered at the Pacific?