Yue Tian
Yue Tian

Reputation: 11

Do not plot gridlines/contourlines/coastlines outside of the canvas with cartopy

I'm plotting a map panel with cartopy in eps format. The resulting plot looks fine but has very broad margins when I insert it into my latex document. When checking the plot with adobe illustrator, it seems like the cartopy plots all the gridlines/contourlines/coastlines, even those outside of the canvas, which are hidden but do take up some spaces in the plot.

I tried to use constrained_layout and tight_layout, but they are incompatible with subplots_adjust which I use for adding the shared colorbar.

The code I use to plot is as follows:

proj2 = ccrs.LambertConformal(central_longitude=0, central_latitude=50)
proj_lonlat = ccrs.PlateCarree()
fig = plt.figure(figsize=(12, 9), constrained_layout=True)

# define a function to plot
def plot_era5_500z_MSLp(f500, fsurf, time, label, ax):
    # read data
    for i in np.arange(len(f500.time.values)):
        if pd.to_datetime(f500.time.values[i]) == pd.to_datetime(time):
            print('processing time: ' + time)
            lons = f500.longitude.values         # 1-d array
            lats = f500.latitude.values          # 1-d array
            gph500 = f500.z.values[i,:,:]/98     # geopotential (m2 s-2) -> geopotential height (dagpm) [time = 72, lat = 241, lon = 561]
            pmsl = fsurf.msl.values[i,:,:]/100      # mean sea level pressure    Pa -> hPa
    
    # create base map
    ax.set_extent([-35, 30, 25, 70])   # x0, x1, y0, y1
    gl = ax.gridlines(crs=proj_lonlat, draw_labels=True, xlocs=[-60,-40,-20,0,20,40,60], ylocs=[20,30,40,50,60],
                      x_inline=False, y_inline=False, color='k', alpha=0.5, linestyle='dotted')
    gl.top_labels=False
    gl.right_labels=False
    gl.xlabel_style = {'size': 14, 'color': 'k'}
    gl.ylabel_style = {'size': 14, 'color': 'k'}
    gl.rotate_labels = False
    ax.add_feature(cfeature.COASTLINE.with_scale('50m'), lw=0.4, alpha=0.9)   # add coastline feature
    
    # plot 500hPa geopotential height  (zc: z contour)
    z_levels = np.arange(500, 580+10, 8)
    zc = ax.contour(lons, lats, gph500, transform=proj_lonlat, 
                    levels=z_levels, extent='both', colors='mediumblue', linewidths=0.5)
    ax.clabel(zc, inline=True, fontsize=10, fmt='%.0f')
    
    # plot MSL pressure (mslps: MSL p shading; mslpc: MSL p contour)
    levels = np.arange(960, 1057, 4)
    mslps = ax.contourf(lons, lats, pmsl, levels=levels, cmap='Spectral_r', transform=proj_lonlat)
    mslpc = ax.contour(lons, lats, pmsl, levels=levels, colors='k', linewidths=0.5, alpha=0.6, transform=proj_lonlat)
    
    ax.set_title(label + ' ' + time, loc= 'left', pad=0.5, fontsize=14)
    return mslps
    

# fig (a)
ax1 = plt.subplot(2, 2, 1, projection=proj2)
plot_era5_500z_MSLp(f500_2016nov, fsurf_2016nov, '2016-11-20 12:00', '(a)', ax1)

# fig (b)
ax2 = plt.subplot(2, 2, 2, projection=proj2)
plot_era5_500z_MSLp(f500_2016nov, fsurf_2016nov, '2016-11-24 00:00', '(b)', ax2)

# fig (c)
ax3 = plt.subplot(2, 2, 3, projection=proj2)
plot_era5_500z_MSLp(f500_2017feb, fsurf_2017feb, '2017-02-27 18:00', '(c)', ax3)

# fig (4)
ax4 = plt.subplot(2, 2, 4, projection=proj2)
mslps = plot_era5_500z_MSLp(f500_2017mar, fsurf_2017mar, '2017-03-04 06:00', '(d)', ax4)   # only return mslps here for plotting the sharred colorbar


fig.subplots_adjust(right=0.8, wspace=0.2, hspace=0.000001)
cbar_ax = fig.add_axes([0.82, 0.2, 0.02, 0.55])    # left border, bottom border, width, height
cbar = fig.colorbar(mslps, cax=cbar_ax)
cbar.set_label(label='Mean sea level pressure (hPa)', size=16)
cbar.ax.tick_params(labelsize=14)

The resulting eps plot looks good, but in adobe illustrator, one can see the excess lines outside of the canvas:

for subplots with lines extending beyond axis boundaries

Is there any way I can limit the plotting range of the data, or disable the lines outside of the canvas?

Upvotes: 1

Views: 255

Answers (0)

Related Questions