Search code examples
pythonpython-2.7matplotlibcartopy

Cartopy set_extent is not working


I am trying to use Mateplotlib cartopy to make the plots below. Here is the code that I am using.

import cartopy.crs as ccrs

fig=plt.figure(figsize=(15,11))
ax = plt.subplot(111, projection=ccrs.PlateCarree(central_longitude=0))
mm =   ax.contourf(new_lon[:],lat_post,new_aa[0,:,:],transform=ccrs.PlateCarree(central_longitude=0))

ax.coastlines(resolution='10m');
ax.stock_img();
# the following two lines increaes the vertical distance between the title and the upper tick.
from matplotlib import rcParams
rcParams['axes.titlepad']=20
# drawing the longitude and latitude ticks.
gl = ax.gridlines(crs=ccrs.PlateCarree(central_longitude=0), draw_labels=True,linewidth=2, color='gray', alpha=0.5, linestyle='--')

enter image description here Yet, once I add the following code set_extent ax.set_extent([np.min(new_lon),np.max(new_lon),np.min(lat_post) ,np.max(lat_post)])

The figures becomes like that enter image description here


Solution

  • Looking at your original map, it looks like there's a seam at 0 longitude, so I'm guessing np.min(new_lon) is 0, and np.min(new_lon) is 360. If you use that with set_extent(), you're getting a really narrow strip at the prime meridian. I'm guess if you do set_extent([-180, 180, ,np.min(lat_post), np.max(lat_post)] it will work better.

    The only way I can think of to achieve it programmatically in this case is to do:

    lon_bounds = new_lon[:]  # copy
    lon_bounds[lon_bounds > 180] -= 360
    ax.set_extent([np.min(lon_bounds), np.max(lon_bounds), np.min(lat_post), np.max(lat_post)])