def format_contour_axes(ax): """ Format the axes limits, tick marks, and tick labels for the contour plots Args: ax (:class: 'matplotlib.Axes'): The set of axes to be manipulated """ # Use geocat.viz.util convenience function to set axes tick values gvutil.set_axes_limits_and_ticks(ax=ax, xlim=(-180, 180), ylim=(-90, 90), xticks=np.arange(-180, 181, 30), yticks=np.arange(-90, 91, 30)) # Use geocat.viz.util convenience function to add minor and major ticks gvutil.add_major_minor_ticks(ax, labelsize=8) # 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) # Remove the degree symbol from tick labels ax.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol='')) ax.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol='')) # Use geocat.viz.util convenience function to set titles and labels gvutil.set_titles_and_labels(ax, maintitle='300mb', maintitlefontsize=8)
def _set_NCL_style(self, ax, fontsize=18, subfontsize=18, labelfontsize=16): # Set NCL-style tick marks # TODO: switch from using geocat-viz to using a geocat-lynx specific tick function add_major_minor_ticks(ax, labelsize=10) # Set NLC-style titles set from from initialization call (based on geocat-viz function) if self.maintitle is not None: if self.lefttitle is not None or self.righttitle is not None: plt.title(self.maintitle, fontsize=fontsize + 2, y=1.12) else: plt.title(self.maintitle, fontsize=fontsize, y=1.04) if self.lefttitle is not None: plt.title(self.lefttitle, fontsize=subfontsize, y=1.04, loc='left') if self.righttitle is not None: plt.title(self.righttitle, fontsize=subfontsize, y=1.04, loc='right') if self.xlabel is not None: plt.xlabel(self.xlabel, fontsize=labelfontsize) if self.ylabel is not None: plt.ylabel(self.ylabel, fontsize=labelfontsize) # format axes as lat lon add_lat_lon_ticklabels(self.ax)
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(color, row, col, pos, title): # Generate axes, using Cartopy, drawing coastlines, and adding features projection = ccrs.PlateCarree() ax1 = plt.subplot(row, col, pos, projection=projection) ax1.coastlines(linewidths=0.5) ax1.add_feature(cfeature.LAND, facecolor="lightgray") # Import an NCL colormap newcmp = color # Contourf-plot data hgt = t.plot.contourf(ax=ax1, transform=projection, levels=40, vmin=100, vmax=1600, cmap=newcmp, add_colorbar=False) # Add color bar cbar_ticks = np.arange(100, 1600, 100) cbar = plt.colorbar(hgt, orientation='vertical', shrink=0.8, pad=0.05, extendrect=True, ticks=cbar_ticks) cbar.ax.tick_params(labelsize=10) # Use geocat.viz.util convenience function to set axes parameters without calling several matplotlib functions # Set axes limits, and tick values gvutil.set_axes_limits_and_ticks(ax1, xlim=(0, 90), ylim=(0, 90), xticks=np.linspace(-180, 180, 13), yticks=np.linspace(-90, 90, 7)) # Use geocat.viz.util convenience function to make plots look like NCL plots by using latitude, longitude tick labels gvutil.add_lat_lon_ticklabels(ax1) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax1, labelsize=12) # Use geocat.viz.util convenience function to set titles and labels without calling several matplotlib functions gvutil.set_titles_and_labels(ax1, maintitle=title, maintitlefontsize=16, righttitlefontsize=14, xlabel="", ylabel="")
def make_contour_plot(ax, dataset): lat = dataset['lat'] lon = dataset['lon'] values = dataset.data # Import an NCL colormap cmap = gvcmaps.BlWhRe # Specify contour levelstamam v = np.linspace(-0.08, 0.08, 9, endpoint=True) # The function contourf() produces fill colors, and contour() calculates contour label locations. cplot = ax.contourf(lon, lat, values, levels=v, cmap=cmap, extend="both", transform=ccrs.PlateCarree()) p = ax.contour(lon, lat, values, levels=v, linewidths=0.0, transform=ccrs.PlateCarree()) # Label the contours ax.clabel(p, fontsize=8, fmt="%0.2f", colors="black") # 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, x_minor_per_major=3, y_minor_per_major=4, labelsize=10) # Use geocat.viz.util convenience function to set axes tick values gvutil.set_axes_limits_and_ticks(ax, xticks=[-60, -30, 0, 30], yticks=[40, 60, 80]) # Use geocat.viz.util convenience function to make plots look like NCL plots, using latitude & longitude tick labels gvutil.add_lat_lon_ticklabels(ax) return cplot, ax
def Plot(color, row, col, pos, title): # Generate axes, using Cartopy, drawing coastlines, and adding features projection = ccrs.PlateCarree() ax1 = plt.subplot(row, col, pos, projection=projection) ax1.coastlines(linewidths=0.5) ax1.add_feature(cfeature.LAND, facecolor="lightgray") # Import an NCL colormap newcmp = color #gvcmaps.BlAqGrYeOrRe # Contourf-plot data t.plot.contourf(ax=ax1, transform=projection, levels=40, vmin=100, vmax=1600, cmap=newcmp, cbar_kwargs={ "orientation": "vertical", "ticks": np.arange(100, 1600, 100), "label": "", "shrink": 0.8 }) # Use geocat.viz.util convenience function to set axes parameters without calling several matplotlib functions # Set axes limits, and tick values gvutil.set_axes_limits_and_ticks(ax1, xlim=(0, 90), ylim=(0, 90), xticks=np.linspace(-180, 180, 13), yticks=np.linspace(-90, 90, 7)) # Use geocat.viz.util convenience function to make plots look like NCL plots by using latitude, longitude tick labels gvutil.add_lat_lon_ticklabels(ax1) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax1, labelsize=12) # Use geocat.viz.util convenience function to set titles and labels without calling several matplotlib functions gvutil.set_titles_and_labels(ax1, maintitle=title, maintitlefontsize=16, righttitlefontsize=14, xlabel="", ylabel="")
def make_shared_plot(title): # Generate figure (set its size (width, height) in inches) and axes using Cartopy projection plt.figure(figsize=(10, 5.5)) ax = plt.axes(projection=ccrs.PlateCarree()) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax, x_minor_per_major=4, y_minor_per_major=5, labelsize=14) # 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 set axes limits & tick values without calling several matplotlib functions gvutil.set_axes_limits_and_ticks(ax, xlim=(-125, -70), ylim=(25, 50), xticks=range(-120, -75, 20), yticks=range(30, 51, 10)) # Turn on continent shading ax.add_feature(cartopy.feature.LAND, edgecolor='lightgray', facecolor='lightgray', zorder=0) ax.add_feature(cartopy.feature.LAKES, edgecolor='white', facecolor='white', zorder=0) # Scatter-plot the location data on the map scatter = plt.scatter(lon, lat, c=dummy_data, cmap=cmap, zorder=1) plt.title(title, fontsize=16, y=1.04) return scatter, ax
# we only read every third latitude and longitude. # This choice was made because ``geocat.viz`` doesn't offer an # equivalent function to ncl's ``vcMinDistanceF`` yet. file_in = xr.open_dataset('../../data/netcdf_files/uv300.nc') # Our dataset is a subset of the data from the file ds = file_in.isel(time=1, lon=slice(0, -1, 3), lat=slice(1, -1, 3)) ############################################################################### # Make the plot # Set up figure and axes fig, ax = plt.subplots(figsize=(10, 5.25)) ax = plt.axes(projection=ccrs.PlateCarree()) 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 # Notes # 1. We plot every third vector in each direction, which is not as nice as vcMinDistanceF in NCL # 2. There is no matplotlib equivalent to "CurlyVector" Q = plt.quiver(ds['lon'], ds['lat'], ds['U'].data, ds['V'].data, color='black', zorder=1,
52.7, '500hPa', transform=projection, fontsize=18, ha='center', va='center', color='mediumorchid', bbox=props) # Use geocat.viz.util convenience function to set axes tick values gvutil.set_axes_limits_and_ticks(ax, xticks=[100, 120, 140], yticks=[20, 30, 40, 50]) # 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 minor and major tick lines gvutil.add_major_minor_ticks(ax, x_minor_per_major=4, y_minor_per_major=5, labelsize=18) # 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="Temp", lefttitlefontsize=20, righttitle="Wind", righttitlefontsize=20) # Show the plot
# Add coastlines to the subplots ax.coastlines() # 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 set axes limits & tick # values without calling several matplotlib functions gvutil.set_axes_limits_and_ticks(ax, ylim=(-60, 60), xticks=np.linspace(-180, 180, 13), yticks=np.linspace(-60, 60, 5)) # 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, zero_direction_label=True) # Add color bar and label details (title, size, etc.) cax = axgr.cbar_axes[0] cax.colorbar(p) axis = cax.axis[cax.orientation] axis.label.set_text(r'Temperature ($^{\circ} C$)') axis.label.set_size(16) axis.major_ticklabels.set_size(10) # Save figure and show plt.savefig('linint2_points.png', dpi=300) plt.show()
def Plot(color, ext, xext, yext, npts, title, subt, style, pt): """ Helper function to create two similar plots where color, extent, title, line style, and marker style can all be customized on the same style map projection. Args: color (:class: 'str'): color for line on map in format 'color' ext (:class: 'list'): extent of the projection view in format [minlon, maxlon, minlat, maxlat] xext (:class: 'list'): start and stop points for curve in format [startlon, stoplon] yext (:class: 'list'): start and stop points for curve in format [startlat, stoplat] title (:class: 'str'): title of graph in format "Title" style (:class: 'str'): line style in format 'style' pt (:class: 'str'): marker type in format 'type' """ plt.figure(figsize=(8, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(ext, ccrs.PlateCarree()) ax.add_feature(cfeature.LAND, color="lightgrey") # This gets geodesic between the two points # WGS84 ellipsoid is used # yext and xext refer to the start and stop points for the curve # [0] being start, [1] being stop gl = Geodesic.WGS84.InverseLine(yext[0], xext[0], yext[1], xext[1]) npoints = npts # Compute points on the geodesic, and plot them # gl.s13 is the total length of the geodesic # the points are equally spaced by 'true distance', but visually # there is a slight distortion due to curvature/projection style lons = [] lats = [] for ea in np.linspace(0, gl.s13, npoints): g = gl.Position(ea, Geodesic.STANDARD | Geodesic.LONG_UNROLL) lon2 = g["lon2"] lat2 = g["lat2"] lons.append(lon2) lats.append(lat2) plt.plot(lons, lats, style, color=color, transform=ccrs.Geodetic()) ax.plot(lons, lats, pt, transform=ccrs.PlateCarree()) plt.suptitle(title, y=0.90, fontsize=16) # Use geocat.viz.util convenience function to set axes parameters without calling several matplotlib functions # Set axes limits, and tick values gvutil.set_axes_limits_and_ticks( ax, xlim=(-125, -60), ylim=(15, 65), xticks=np.linspace(-180, 180, 13), yticks=np.linspace(0, 80, 5), ) # 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) # Remove the degree symbol from tick labels ax.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol="")) ax.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol="")) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax, labelsize=12) # Use geocat.viz.util convenience function to set titles and labels without calling several matplotlib functions gvutil.set_titles_and_labels( ax, maintitle=subt, maintitlefontsize=12, xlabel="", ylabel="" ) plt.show()
# Use geocat.viz.util convenience function to add left and right title to the plot axes. gvutil.set_titles_and_labels(ax[2], lefttitle="Vector Wind", lefttitlefontsize=12, righttitle=ds.U.units, righttitlefontsize=12) # cartopy axes require this to be manual ax[2].set_xticks(kwargs["xticks"]) ax[2].set_yticks(kwargs["yticks"]) # Use geocat.viz.util convenience function to add minor and major tick lines [gvutil.add_major_minor_ticks(axes) for axes in ax.flat] # Use geocat.viz.util convenience function to make plots look like NCL plots by using latitude, longitude tick labels [gvutil.add_lat_lon_ticklabels(axes) for axes in ax.flat] # Remove degree markers from x and y labels [ axes.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol='')) for axes in ax.flat ] [ axes.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol='')) for axes in ax.flat ] # Display plot plt.show()
def make_base_plot(): # Generate axes using Cartopy projection ax = plt.axes(projection=ccrs.PlateCarree()) # Add continents continents = cartopy.feature.NaturalEarthFeature( name="coastline", category="physical", scale="50m", edgecolor="None", facecolor="lightgray", ) ax.add_feature(continents) # Set map extent ax.set_extent([-130, 0, -20, 40], crs=ccrs.PlateCarree()) # Define the contour levels. The top range value of 44 is not included in the levels. levels = np.arange(-12, 44, 4) # Using a dictionary prevents repeating the same keyword arguments twice for the contours. kwargs = dict( levels=levels, # contour levels specified outside this function xticks=[-120, -90, -60, -30, 0], # nice x ticks yticks=[-20, 0, 20, 40], # nice y ticks transform=ccrs.PlateCarree(), # ds projection add_colorbar=False, # don't add individual colorbars for each plot call add_labels=False, # turn off xarray's automatic Lat, lon labels colors="gray", # note plurals in this and following kwargs linestyles="-", linewidths=0.5, ) # Contourf-plot data (for filled contours) hdl = ds.U.plot.contour(x="lon", y="lat", ax=ax, **kwargs) # Add contour labels. Default contour labels are sparsely placed, so we specify label locations manually. # Label locations only need to be approximate; the nearest contour will be selected. label_locations = [ (-123, 35), (-116, 17), (-94, 4), (-85, -6), (-95, -10), (-85, -15), (-70, 35), (-42, 28), (-54, 7), (-53, -5), (-39, -11), (-28, 11), (-16, -1), (-8, -9), # Python allows trailing list separators. ] ax.clabel( hdl, np.arange(-8, 24, 8), # Only label these contour levels: [-8, 0, 8, 16] fontsize="small", colors="black", fmt="%.0f", # Turn off decimal points manual=label_locations, # Manual label locations inline=False ) # Don't remove the contour line where labels are located. # Create a rectangle patch, to color the border of the rectangle a different color. # Specify the rectangle as a corner point with width and height, to help place border text more easily. left, width = -90, 45 bottom, height = 0, 30 right = left + width top = bottom + height # Draw rectangle patch on the plot p = plt.Rectangle( (left, bottom), width, height, fill=False, zorder=3, # Plot on top of the purple box border. edgecolor='red', alpha=0.5) # Lower color intensity. ax.add_patch(p) # Draw text labels around the box. # Change the default padding around a text box to zero, making it a "tight" box. # Create "text_args" to keep from repeating code when drawing text. text_shared_args = dict( fontsize=8, bbox=dict(boxstyle='square, pad=0', facecolor='white', edgecolor='white'), ) # Draw top text ax.text(left + 0.6 * width, top, 'test', horizontalalignment='right', verticalalignment='center', **text_shared_args) # Draw bottom text. Change text background to match the map. ax.text( left + 0.5 * width, bottom, 'test', horizontalalignment='right', verticalalignment='center', fontsize=8, bbox=dict(boxstyle='square, pad=0', facecolor='lightgrey', edgecolor='lightgrey'), ) # Draw left text ax.text(left, top, 'test', horizontalalignment='center', verticalalignment='top', rotation=90, **text_shared_args) # Draw right text ax.text(right, bottom, 'test', horizontalalignment='center', verticalalignment='bottom', rotation=-90, **text_shared_args) # Add lower text box. Box appears off-center, but this is to leave room # for lower-case letters that drop lower. ax.text(1.0, -0.20, "CONTOUR FROM -12 TO 40 BY 4", fontname='Helvetica', horizontalalignment='right', transform=ax.transAxes, bbox=dict(boxstyle='square, pad=0.15', facecolor='white', edgecolor='black')) # 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="Zonal Wind", lefttitlefontsize=12, righttitle="m/s", righttitlefontsize=12) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(ax, y_minor_per_major=4) # 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) return ax
ylim=[-90, 90], xticks=np.arange(-180, 181, 30), yticks=np.arange(-90, 91, 30)) gvutil.set_axes_limits_and_ticks(axs[1], xlim=[-180, 180], ylim=[-90, 90], xticks=np.arange(-180, 181, 30), yticks=np.arange(-90, 91, 30)) # Use geocat.viz.util convenience function to add minor and major tick lines gvutil.add_major_minor_ticks(axs[0]) gvutil.add_major_minor_ticks(axs[1]) # Use geocat.viz.util convenience function to make plots look like NCL plots by # using latitude, longitude tick labels gvutil.add_lat_lon_ticklabels(axs[0]) gvutil.add_lat_lon_ticklabels(axs[1]) # Remove the degree symbol from tick labels axs[0].yaxis.set_major_formatter(LatitudeFormatter(degree_symbol='')) axs[0].xaxis.set_major_formatter(LongitudeFormatter(degree_symbol='')) axs[1].yaxis.set_major_formatter(LatitudeFormatter(degree_symbol='')) axs[1].xaxis.set_major_formatter(LongitudeFormatter(degree_symbol='')) # Use geocat.viz.util convenience function to set titles and labels gvutil.set_titles_and_labels(axs[0], lefttitle='Speed', lefttitlefontsize=10, righttitle=U.units, righttitlefontsize=10) gvutil.set_titles_and_labels(axs[1], lefttitle='Wind',