def plot_labelled_filled_contours(data, ax=None): """ A utility function for convenience that plots labelled, filled contours with black contours marking each level.It will return a dictionary containing three objects corresponding to the filled contours, the black contours, and the contour labels. """ # Import an NCL colormap, truncating it by using geocat.viz.util convenience function newcmp = gvutil.truncate_colormap(gvcmaps.gui_default, minval=0.03, maxval=0.9) handles = dict() handles["filled"] = data.plot.contourf( ax=ax, # this is the axes we want to plot to cmap=newcmp, # our special colormap levels=levels, # contour levels specified outside this function xticks=np.arange(-180, 181, 30), # nice x ticks yticks=np.arange(-90, 91, 30), # nice y ticks transform=projection, # data projection add_colorbar=False, # don't add individual colorbars for each plot call add_labels=False, # turn off xarray's automatic Lat, lon labels ) # matplotlib's contourf doesn't let you specify the "edgecolors" (MATLAB terminology) # instead we plot black contours on top of the filled contours handles["contour"] = data.plot.contour( ax=ax, levels=levels, colors="black", # note plurals in this and following kwargs linestyles="-", linewidths=0.5, add_labels=False, # again turn off automatic labels ) # Label the contours ax.clabel( handles["contour"], fontsize=8, fmt="%.0f", # Turn off decimal points ) # Add coastlines ax.coastlines(linewidth=0.5) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax) # Use geocat.viz.util convenience function to make plots look like NCL plots by using latitude, longitude tick labels gvutil.add_lat_lon_ticklabels(ax) # Use geocat.viz.util convenience function to add main title as well as titles to left and right of the plot axes. gvutil.set_titles_and_labels(ax, lefttitle=data.attrs['long_name'], lefttitlefontsize=10, righttitle=data.attrs['units'], righttitlefontsize=10) return handles
def plot_labelled_filled_contours(data, ax=None): """ A utility function for convenience that plots labelled, filled contours with black contours marking each level.It will return a dictionary containing three objects corresponding to the filled contours, the black contours, and the contour labels. """ cmap = truncate_colormap(mpl.cm.rainbow, 0.2, 0.9) handles = dict() handles["filled"] = data.plot.contourf( ax=ax, # this is the axes we want to plot to cmap=cmap, # our special colormap levels=levels, # contour levels specified outside this function xticks=np.arange(-180, 181, 30), # nice x ticks yticks=np.arange(-90, 91, 30), # nice y ticks transform=ccrs.PlateCarree(), # data projection add_colorbar=False, # don't add individual colorbars for each plot call add_labels=False, # turn off xarray's automatic Lat, lon labels ) # matplotlib's contourf doesn't let you specify the "edgecolors" (MATLAB terminology) # instead we plot black contours on top of the filled contours handles["contour"] = data.plot.contour( ax=ax, levels=levels, colors="k", # note plurals in this and following kwargs linestyles="-", linewidths=0.5, add_labels=False, # again turn off automatic labels ) # Label the contours ax.clabel( handles["contour"], fontsize="small", fmt="%.0f", # Turn off decimal points ) # make a nice title title = f"{data.attrs['long_name']} [{data.attrs['units']}]" ax.set_title(title, loc="left", y=1.05) return handles
############################################################################### # Plot: # ----- # Generate figure (set its size (width, height) in inches) and axes using Cartopy fig = plt.figure(figsize=(10, 10)) ax = plt.axes(projection=projection) ax.set_extent([100, 145, 15, 55], crs=projection) # Define the contour levels clevs = np.arange(228, 273, 4, dtype=float) # Import an NCL colormap, truncating it by using geocat.viz.util convenience function newcmp = gvutil.truncate_colormap(gvcmaps.BkBlAqGrYeOrReViWh200, minval=0.1, maxval=0.6, n=len(clevs)) # Draw the temperature contour plot with the subselected colormap # (Place the zorder of the contour plot at the lowest level) cf = ax.contourf(lon, lat, T, levels=clevs, cmap=newcmp, zorder=1) # Draw horizontal color bar cax = plt.axes((0.14, 0.08, 0.74, 0.02)) cbar = plt.colorbar(cf, ax=ax, cax=cax, ticks=clevs[1:-1], drawedges=True, orientation='horizontal') cbar.ax.tick_params(labelsize=12)
# Plot contour lines lines = percentage.plot.contour(ax = ax, levels = levels, colors = 'black', linewidths = 0.5, linestyles = 'solid', add_labels = False) # Draw contour labels and set their backgrounds to be white ax.clabel(lines, fmt = '%d', levels = levels) [ txt.set_bbox(dict(facecolor = 'white', edgecolor = 'none', pad = 1)) for txt in lines.labelTexts ] # Import Color map cmap = gvcmap.BlueRed # Truncate colormap to only use the light blue colors and the reds cmap = gvutil.truncate_colormap(cmap, minval = 0.31, maxval = 1, n = 10) # on ncl 78-253 # Plot filled contours colors = percentage.plot.contourf(ax = ax, levels = levels, cmap = cmap, add_labels = False, add_colorbar = False) # Add colorbar plt.colorbar(colors, ax = ax, orientation = 'vertical', ticks = levels[1::2], drawedges = True, aspect = 12, shrink = 0.7, pad = 0.1) # Look up slice notation on levels[1::2] # Use geocat.viz.util convenience function to set axes tick values # Set y-lim in order for y-axis to have descending values gvutil.set_axes_limits_and_ticks(ax, xlim = (0, 90), xticks = np.arange(0, 80, 20), ylim = (0, 1000), yticks = np.arange(0, 1000, 200)) # Force the plot to be square by setting the aspect ratio to 1 ax.set_box_aspect(1) plt.tight_layout() # automatically adjust subplot parameters to give specified padding
# Set up figure and axes fig, ax = plt.subplots(figsize=(10, 6.25)) ax = plt.axes(projection=ccrs.PlateCarree()) fig.suptitle('Vectors colored by a scalar map', fontsize=14, y=.9) nclize_axis(ax) add_lat_lon_ticklabels(ax) # Set major and minor ticks plt.xticks(range(-180, 181, 30)) plt.yticks(range(-90, 91, 30)) # Draw vector plot # (there is no matplotlib equivalent to "CurlyVector" yet) plt.cm.register_cmap( 'BlAqGrYeOrReVi200', truncate_colormap(cmaps.BlAqGrYeOrReVi200, minval=0.03, maxval=0.95, n=16)) cmap = plt.cm.get_cmap('BlAqGrYeOrReVi200', 16) Q = plt.quiver(ds['lon'], ds['lat'], ds['U'].data, ds['V'].data, ds['T'].data, cmap=cmap, zorder=1, pivot="middle", width=0.001) plt.clim(228, 292) # Draw legend for vector plot ax.add_patch( plt.Rectangle((150, -140),
y = 1.05 ax1.set_title('Time(0)', fontsize=size, y=y) ax1.set_title(TS_0.long_name, fontsize=size, loc='left', y=y) ax1.set_title(TS_0.units, fontsize=size, loc='right', y=y) # Plot zonal mean temperature ax2.plot(mean.data, mean.lat, color='black', linewidth=0.5) # Plot vertical reference line in zonal mean plot ax2.axvline(273.15, color='black', linewidth=0.5) # Import color map cmap = gvcmaps.BlWhRe # Truncate colormap to only use paler colors in the center of the colormap cmap = gvutil.truncate_colormap(cmap, minval=0.22, maxval=0.74, n=14) # Plot filled contour for deviation from time avg plot deviations = time_dev.plot.contourf(ax=ax3, transform=proj, vmin=-14, vmax=18, levels=np.arange(-14, 20, 2), cmap=cmap, add_colorbar=False, add_labels=False) # Draw contour lines for deviation from time avg plot time_dev.plot.contour(ax=ax3, transform=proj, vmin=-14,
ocean_only = gvutil.xr_add_cyclic_longitudes(ocean_only, "lon") ############################################################################### # Plot Ocean Only: # Generate figure (set its size (width, height) in inches) plt.figure(figsize=(10, 6)) # Generate axes using Cartopy and draw coastlines projection = ccrs.PlateCarree() ax = plt.axes(projection=projection) ax.coastlines(linewidth=0.5, resolution="110m") # Import an NCL colormap, truncating it by using geocat.viz.util convenience function newcmp = gvutil.truncate_colormap(gvcmaps.BlAqGrYeOrRe, minval=0.1, maxval=1.0, n=22) # Contourf-plot ocean-only data (for filled contours) filled = ocean_only.plot.contourf(ax=ax, cmap=newcmp, levels=np.arange(260, 305, 2), xticks=np.arange(-180, 181, 30), yticks=np.arange(-90, 91, 30), transform=ccrs.PlateCarree(), add_colorbar=False, add_labels=False, vmin=260, vmax=304) # Add horizontal colorbar
# Draw legend for vector plot qk = ax.quiverkey(Q, 94, 26, 4, r'4 $m/s$', labelpos='N', zorder=2, coordinates='data', color='black') # Draw SST contours truncate_colormap(cmaps.BlAqGrYeOrReVi200, minval=0.08, maxval=0.96, n=len(levels), name='BlAqGrYeOrReVi200') cf = sst.plot.contourf('lon', 'lat', extend='both', levels=levels, cmap='BlAqGrYeOrReVi200', zorder=0, xlabel='', add_labels=False, cbar_kwargs={ 'shrink': 0.75, 'ticks': np.linspace(24, 28.8, 17), 'drawedges': True, 'label': '$^\circ$C'
) # make a nice title ax.set_title(f"{data.attrs['long_name']}", loc="left", y=1.05) ax.set_title(f"{data.attrs['units']}", loc="right", y=1.05) return filled ############################################################################### # Plot Ocean Only # =============== levels = np.arange(260, 305, 2) plt.register_cmap("BlAqGrYeOrRe", truncate_colormap(cmaps.BlAqGrYeOrRe, 0.1, 1.0)) cmap = plt.cm.get_cmap("BlAqGrYeOrRe", 22) f, ax = plt.subplots(1, 1, subplot_kw={"projection": ccrs.PlateCarree()}) filled = plot_filled_contours(ocean_only, vmin=260, vmax=304, ax=ax, cmap=cmap) cbar = f.colorbar( filled, # make colorbar appropriate for this object ax= ax, # a list of *two* axes, matplotlib will steal space from both these to fit the colorbar orientation= "horizontal", # horizontal colorbars are on the bottom by default aspect=30, # aspect ratio of colorbar, just because we can. drawedges=True, )