示例#1
0
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)
示例#2
0
    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)
示例#3
0
def make_bar_plot(ax, dataset):
    years = list(dataset.time.dt.year)
    values = list(dataset.values)
    colors = ['blue' if val < 0 else 'red' for val in values]

    ax.bar(years,
           values,
           color=colors,
           width=1.0,
           edgecolor='black',
           linewidth=0.5)
    ax.set_ylabel('Pa')

    # 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=8)

    # Use geocat.viz.util convenience function to set axes tick values
    gvutil.set_axes_limits_and_ticks(ax,
                                     xticks=np.linspace(1980, 2000, 6),
                                     xlim=[1978.5, 2003.5])

    return ax
示例#4
0
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
示例#5
0
def radar_plot(X, Y, values, bg_color=None):
    # Create a figure and axes using subplots
    fig, ax = plt.subplots(figsize=(6, 8))

    # Choose default colormap
    cmap = gvcmaps.gui_default

    # Plot using contourf
    p = plt.contourf(X,
                     Y,
                     values,
                     cmap=cmap,
                     levels=np.arange(-20, 70, 5) * 100,
                     zorder=3)

    # Change orientation and tick marks of colorbar
    plt.colorbar(p,
                 orientation="horizontal",
                 ticks=np.arange(-15, 65, 15) * 100,
                 drawedges=True,
                 aspect=12)

    # 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 add titles to left and right of the plot axis.
    gvutil.set_titles_and_labels(ax,
                                 lefttitle=ds.DZ.long_name,
                                 lefttitlefontsize=16,
                                 righttitle=ds.DZ.units,
                                 righttitlefontsize=16,
                                 xlabel="",
                                 ylabel="")

    # Use geocat.viz.util convenience function to set axes limits & tick values
    gvutil.set_axes_limits_and_ticks(ax,
                                     xlim=(-240, 240),
                                     ylim=(-240, 240),
                                     xticks=np.arange(-200, 201, 100),
                                     yticks=np.arange(-200, 201, 100))

    # Use geocat.viz.util convenience function to set tick placements
    gvutil.add_major_minor_ticks(ax,
                                 x_minor_per_major=5,
                                 y_minor_per_major=5,
                                 labelsize=14)

    # Set aspect ratio
    ax.set_aspect('equal')

    # Allow optional background circle to be set
    if (bg_color is not None):
        circle_bg = plt.Circle((0, 0), 240, color=bg_color, zorder=1)
        ax.add_artist(circle_bg)

    # Show plot
    plt.show()
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="")
示例#7
0
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
示例#8
0
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="")
示例#9
0
def format_linegraph_axes(ax):
    """
    Format the axes limits, tick marks, and tick labels for the line graphs

    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=(-90, 90),
        ylim=(-20, 50),
        xticks=np.arange(-90, 91, 30),
        yticks=np.arange(-20, 51, 10),
        xticklabels=['90S', '60S', '30S', '0', '30N', '60N', '90N'])

    # Use geocat.viz.util convenience function to add minor and major ticks
    gvutil.add_major_minor_ticks(ax,
                                 x_minor_per_major=3,
                                 y_minor_per_major=5,
                                 labelsize=12)
示例#10
0
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
示例#11
0
# but it uses Xarray's convenient DatetimeAccessor functionality.
time = gavan.time.dt.year

# Plot data and add a legend
ax.plot(time, obs_avg, color='black', label='Observations', zorder=4)
ax.plot(time, gavan_avg, color='blue', label='Natural', zorder=3)
ax.plot(time,
        gavav_avg,
        color='red',
        label='Anthropogenic + Natural',
        zorder=2)
ax.legend(loc='upper left', frameon=False, fontsize=18)

# 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=3,
                             labelsize=20)

# 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=(1890, 2000),
                                 ylim=(-0.4, 1),
                                 xticks=np.arange(1900, 2001, step=20),
                                 yticks=np.arange(-0.3, 1, step=0.3))

# Set three titles on top of each other using axes title and texts
ax.set_title('Parallel Climate Model Ensembles', fontsize=24, pad=60.0)
ax.text(0.5,
        1.125,
        'Global Temperature Anomalies',
        fontsize=18,
示例#12
0
# Open a netCDF data file using xarray default engine and load the data into xarrays
ds = xr.open_dataset(gdf.get("netcdf_files/TestData.xy3.nc"))
# Extract a slice of the data
ds = ds.isel(case=0, time=slice(0, 36))

################################################################################
# Plot:

# Generate figure (set its size (width, height) in inches) and axes (with two different y-axes)
fig, ax1 = plt.subplots(figsize=(7, 6.5))

# Plot data
ax1.plot(ds.time, ds.T, color="blue", linestyle="-", linewidth=0.9)

# Usa geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax1, x_minor_per_major=5, labelsize=14)

# Usa 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=(1970, 1973),
                                 ylim=(0.0, 16.0),
                                 yticks=np.arange(0, 17, 3))

# Usa geocat.viz.util convenience function to set titles and labels without calling several matplotlib functions
gvutil.set_titles_and_labels(ax1,
                             maintitle="Curves Offset",
                             xlabel=ds.time.long_name,
                             ylabel=f"{ds.T.long_name} [solid]")

# Create second y-axis
示例#13
0
ds = ds.isel(time=0).drop('time')
ds = ds.isel(lon=0).drop('lon')
ds = ds.isel(lat=42).drop('lat')

###############################################################################
# Plot:

# Generate figure (set its size (width, height) in inches) and axes
plt.figure(figsize=(8, 8))
ax = plt.gca()

# Plot data
plt.plot(ds.data, ds.lev)

# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax, x_minor_per_major=5, y_minor_per_major=4)

# Use geocat.viz.util convenience function to set axes parameters
gvutil.set_axes_limits_and_ticks(ax,
                                 ylim=(1000, 0),
                                 xticks=np.arange(-10, 30, 5))

# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax,
                             maintitle="Profile Plot",
                             xlabel=ds.long_name,
                             ylabel=ds['lev'].long_name)

plt.show()

###############################################################################
示例#14
0
# Create figure and axes using gvutil
fig, axs = plt.subplots(1,
                        3,
                        figsize=(12, 6),
                        sharex='all',
                        sharey='all',
                        gridspec_kw={'wspace': 0})

# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(axs[0],
                                 xticks=np.arange(0, 120, 20),
                                 yticks=np.arange(0, 120, 20),
                                 xticklabels=np.arange(0, 100, 20),
                                 yticklabels=np.arange(0, 100, 20))
# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(axs[0], x_minor_per_major=4, y_minor_per_major=4)
# Specify which edges of the subplot should have tick lines
axs[0].tick_params(axis='both', which='both', left=True, right=False)
# Force subplot to be square
axs[0].set_aspect(aspect='equal')

# Repeat for other subplots with a few changes
gvutil.set_axes_limits_and_ticks(axs[1],
                                 xticks=np.arange(0, 120, 20),
                                 yticks=np.arange(0, 120, 20),
                                 xticklabels=np.arange(0, 100, 20),
                                 yticklabels=np.arange(0, 100, 20))
gvutil.add_major_minor_ticks(axs[1], x_minor_per_major=4, y_minor_per_major=4)
axs[1].tick_params(axis='both', which='both', left=False, right=False)
axs[1].set_aspect(aspect='equal')
示例#15
0
axs[1].coastlines(linewidth=0.5, zorder=1)

# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(axs[0],
                                 xlim=[-180, 180],
                                 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',
示例#16
0
xticklabels = [
    '12z', '', '18z', '', 'Apr29', '', '06z', '', '12z', '', '18z', '',
    'Apr30', '', '06z', '', '12z', '', '18z', '', 'May01', '', '06z', '', '12z'
]

# Use the geocat.viz function to set axes limits and ticks
gvutil.set_axes_limits_and_ticks(axin1,
                                 xlim=[0, 72],
                                 ylim=[0, .5],
                                 xticks=np.arange(0, 75, 3),
                                 yticks=np.arange(0, .6, 0.1),
                                 xticklabels=xticklabels,
                                 yticklabels=yticklabels)

# Use the geocat.viz function to add minor ticks
gvutil.add_major_minor_ticks(axin1, y_minor_per_major=5, labelsize="small")

# Make ticks only show up on bottom, right, and left of inset axis
axin1.tick_params(bottom=True, left=True, right=True, top=False)
axin1.tick_params(which='minor', top=False, bottom=False)

# Plot line chart

# Plot lines depicting the tempht variable
axin2.plot(taus, tempht, color='red')

# Use the geocat.viz function to set the y axis label
gvutil.set_titles_and_labels(axin2, ylabel='Temp at 2m', labelfontsize=12)

# Determine the labels for each tick on the x and y axes
yticklabels = ['59.0', '60.0', '61.0', '62.0', '63.0', '64.0']
示例#17
0
# Took out degree symbols in latitude/longitude
ax.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol=''))
ax.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol=''))

# Use gvutil function to set title of plot
# Set title font to bold using the r"$\bf{_____}$" formatting characters
# Spaces in title will not show up if included in curly brackets
gvutil.set_titles_and_labels(ax,
                             maintitle=r"$\bf{Big}$" + " " +
                             r"$\bf{centered}$" + " " + r"$\bf{title}$",
                             maintitlefontsize=25)

# Use gvutil function to plot three minor ticks for every major tick on axes
gvutil.add_major_minor_ticks(ax,
                             x_minor_per_major=3,
                             y_minor_per_major=3,
                             labelsize="small")

# Make second subplot for legend
ax2 = plt.subplot(grid[-1, 1:], frameon=False)
removeTicks(ax2)

# Create 6 inset axes within subplot for each field in legend
# Inset_axes positional array argument takes four values:
# [starting (bottom left) x coordinate of window, starting y coordinate of window, width of field, height of field]

# Add circle
axin1 = ax2.inset_axes([0.1, 0.8, .1, .1], frameon=False)
removeTicks(axin1)
axin1.add_patch(mpatches.Circle((0.1, 0.1), radius=.1, color='blue'))
axin1.axis('equal')
示例#18
0
# Set axes title
ax[2].set_title("Vector Wind", loc="left", y=1.05)

# 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
示例#19
0
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
示例#20
0
    # Use geocat-viz function to set main title of plot
    gvutil.set_titles_and_labels(axesList[ax],
                                 maintitle=titles[ax],
                                 maintitlefontsize=10)

    # Use geocat-viz function to set limits and tick locations on x and y axes
    gvutil.set_axes_limits_and_ticks(axesList[ax],
                                     xlim=[0, 1],
                                     ylim=[-1.2, 1.2],
                                     yticks=np.arange(-1.5, 1.5, 0.5),
                                     yticklabels=np.arange(-1.5, 1.5, 0.5))

    # Use geocat-viz function to add major and minor ticks on the x and y axes
    gvutil.add_major_minor_ticks(axesList[ax],
                                 x_minor_per_major=4,
                                 y_minor_per_major=5,
                                 labelsize="small")

# Set standard alpha (transparency) value
alpha = 0.4

# Plot first graph:

# Plot x, y, and z lines
line1 = axesList[0].plot(f, x, color='red')
line2 = axesList[0].plot(f, y, color='limegreen')
line3 = axesList[0].plot(f, z, color='blue')

# Plot second graph:

# Plot x, y, and z lines with the same level of transparency
示例#21
0
ax3.coastlines(linewidths=0.25)

# Create axis for colorbar
ax4 = fig.add_subplot(grid[1, 1], aspect=10)

# Format ticks and ticklabels for the map axes
for ax in [ax1, ax3]:
    # Use the geocat.viz function to set axes limits and ticks
    gvutil.set_axes_limits_and_ticks(ax,
                                     xlim=[-180, 180],
                                     ylim=[-90, 90],
                                     xticks=np.arange(-180, 181, 30),
                                     yticks=np.arange(-90, 91, 30))

    # Use the geocat.viz function to add minor ticks
    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)

    # Removing degree symbol from tick labels to resemble NCL example
    ax.yaxis.set_major_formatter(LatitudeFormatter(degree_symbol=''))
    ax.xaxis.set_major_formatter(LongitudeFormatter(degree_symbol=''))

# Use the geocat.viz function to set axes limits and ticks for zonal average plot
gvutil.set_axes_limits_and_ticks(ax2,
                                 xlim=[200, 310],
                                 ylim=[-90, 90],
                                 xticks=[200, 240, 280],
                                 yticks=[])
示例#22
0
x = np.arange(len(months))  # where to draw x ticks
width = 0.2  # width of each bar within the groups

# Create the subplots using a loop
panel = 0
for row in range(0, 2):
    for col in range(0, 2):
        # Use geocat.viz.util convenience function to set axes parameters
        gvutil.set_axes_limits_and_ticks(axs[row][col],
                                         ylim=(0.4, 1.2),
                                         xticks=x,
                                         yticks=np.arange(0.4, 1.4, 0.2),
                                         xticklabels=months)
        # Use geocat.viz.util convenience function to add minor and major tick lines
        gvutil.add_major_minor_ticks(axs[row][col],
                                     x_minor_per_major=1,
                                     y_minor_per_major=4,
                                     labelsize=12)
        # Use geocat.viz.util convenience function to set titles and labels
        gvutil.set_titles_and_labels(axs[row][col],
                                     ylabel='(\u00B0C)',
                                     labelfontsize=14)

        # Add overall figure title
        fig.suptitle('Paneling bar plots, dummy data', size=20, y=0.94)

        # Add data to subplot
        axs[row][col].bar(x - width * 3 / 2,
                          data[panel][0][:],
                          width,
                          edgecolor='black',
                          linewidth=0.25,
示例#23
0
# Draw the key for the quiver plot as a rectangle patch
ax.add_patch(
    plt.Rectangle((155, 65),
                  25,
                  25,
                  facecolor='white',
                  edgecolor='black',
                  zorder=1))

# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(ax,
                                 xticks=range(-180, 181, 30),
                                 yticks=range(-90, 91, 30))

# 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 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 titles to left and right of the plot axis.
gvutil.set_titles_and_labels(ax,
                             lefttitle=ds['U'].long_name,
                             righttitle=ds['U'].units)

# Add timestamp
ax.text(-200, -115, f'Created: {datetime.now()}')

# Show the plot
plt.show()
示例#24
0
plot_y_max = 1.2

# Generate figure
plt.figure(2, figsize=(6, 5))
ax = plt.gca()

# Set width of each column
w = 0.15

# Create subplots for each category
sub = plt.subplot(111)
sub.bar(x+w, obs, width=0.15, color=color_list[0], edgecolor='black', linewidth=0.25, align='center')
sub.bar((x+(2*w)), ccsm2_t42, width=0.15, color=color_list[1], edgecolor='black', linewidth=0.25, align='center')
sub.bar(x+3*w, ccsm3_t42, width=0.15, color=color_list[2], edgecolor='black', linewidth=0.25, align='center')
sub.bar(x+4*w, ccsm3_t85, width=0.15, color=color_list[3], edgecolor='black', linewidth=0.25, align='center')

# Add the legend
plt.legend(['OBS', 'CCSM2 (T42)', 'CCSM3 (T42)', 'CCSM3 (T85)'], loc='lower center', bbox_to_anchor=(0.5, -0.30), ncol=2)

# 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=(0.4, plot_y_max), xticks=x, xticklabels=labels, yticks=np.linspace(0.4, plot_y_max, 5))

# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax, x_minor_per_major=1, y_minor_per_major=4, labelsize=12)

# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax, maintitle='Nino3.4 Monthly Standard Deviation', maintitlefontsize=16, ylabel="("+u'\N{DEGREE SIGN}'+"C)")

# Show the plot
plt.tight_layout()
plt.show()
示例#25
0
        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
plt.show()
示例#26
0
                     fontweight='bold',
                     y=1.04)
    else:
        ax.scatter(newlon, newlat, c=newsst, **common_options, s=25)
        ax.set_title(
            'linint2_points - Bilinear interpolation for 3000 random locations',
            fontsize=14,
            fontweight='bold',
            y=1.04)

    # 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)
示例#27
0
# `ncol` being equal to the number of labels makes it appear horizontal
legend = ax.legend(bbox_to_anchor=(-0.075, -0.2),
                   ncol=numBins,
                   loc='lower left',
                   columnspacing=0.5,
                   frameon=False)
for txt in legend.get_texts():
    txt.set_ha("center")  # horizontal alignment of text item
    txt.set_va("center")  # vertical alignment of text item
    # Move label text so it is centered under the marker
    txt.set_x(-25)  # x-position
    txt.set_y(-20)  # y-position

# Use geocat.viz.util convenience function to set axes parameters
gvutil.set_axes_limits_and_ticks(ax,
                                 xlim=(0, 300),
                                 ylim=(0, 21),
                                 xticks=range(0, 301, 50),
                                 yticks=range(0, 22, 3))

# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax,
                             x_minor_per_major=5,
                             y_minor_per_major=3,
                             labelsize=14)

# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax, maintitle="Scatter plot with grouped markers")

plt.show()
示例#28
0
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()