# Import an NCL colormap
newcmp = gvcmaps.wgne15

# Contourf-plot data (for filled contours)
a = wrap_v.plot.contourf(levels = 14, cmap = newcmp, add_colorbar=False, add_labels=False)
# Contour-plot data (for borderlines)
wrap_v.plot.contour(levels = 14, linewidths=0.5, cmap='k', add_labels=False)

# Add vertical colorbar
clabels = ["-70","-50","-30","-10","10","30","50","70","90","110","130","150"]
cbar = fig.colorbar(a, label='', ticks=np.linspace(-24, 24, 12), shrink=0.4)
cbar.ax.set_yticklabels(clabels)

# 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=(-90,90),
                                     xticks=np.linspace(-180, 180, 13), yticks=np.linspace(-90, 90, 7))

# Use geocat.viz.util convenience function to add minor and major tick lines
gvutil.add_major_minor_ticks(ax, labelsize=10)

# 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="meridional wind component", lefttitlefontsize=14,
                                 righttitle="m/s", righttitlefontsize=14, xlabel="", ylabel="")

# Show the plot
plt.show()
Exemple #2
0
# Set boxplot edge colors
setBoxColor(boxplots, ['blue', 'red', 'green'])

# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(ax,
                                 ylim=(-6.0, 9.0),
                                 yticks=[-3.0, 0.0, 3.0, 6.0])

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

# Use geocat.viz.util convenience function to add title to the plot axis.
gvutil.set_titles_and_labels(ax, maintitle='Box Plot with Polymarkers')

# Make both major and minor ticks point inwards towards the plot
ax.tick_params(direction="in", which='both')

# Get rid of right and top axis spines
removeSpines(ax)

# Set ticks only at left and bottom sides of plot
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

# Add another partially transparent axis on top of the first one
ax2 = ax.inset_axes([0, 0, 1, 1])
ax2.patch.set_alpha(0.2)
Exemple #3
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
# Determine the labels for each tick on the x and y axes
yticklabels = np.array(levels, dtype=np.int)
xticklabels = [
    '12z', '15z', '18z', '21z', 'Apr29', '03z', '06z', '09z', '12z', '15z',
    '18z', '21z', 'Apr30', '03z', '06z', '09z', '12z', '15z', '18z', '21z',
    'May01', '03z', '06z', '09z', '12z'
]

# Make an axis to overlay on top of the contour plot
axin = fig.add_subplot(spec[0, 0])

# Use the geocat.viz function to set the main title of the plot
gvutil.set_titles_and_labels(axin,
                             maintitle='Meteogram for LGSA, 28/12Z',
                             maintitlefontsize=18,
                             ylabel='Pressure (mb)',
                             labelfontsize=12)

# Add a pad between the y axis label and the axis spine
axin.yaxis.labelpad = 5

# Use the geocat.viz function to set axes limits and ticks
gvutil.set_axes_limits_and_ticks(axin,
                                 xlim=[taus[0], taus[-1]],
                                 ylim=[levels[0], levels[-1]],
                                 xticks=np.array(taus),
                                 yticks=np.linspace(1000, 400, 8),
                                 xticklabels=xticklabels,
                                 yticklabels=yticklabels)
Exemple #5
0
# Generate figure (set its size (width, height) in inches) and axes
plt.figure(figsize=(6.2, 6))
ax = plt.gca()

# Scatter-plot the data
plt.scatter(ts_rolled.time, ts_rolled.values, c='r', s=3)

# Plot a regression line
plt.plot(ts.time, regline_vals, 'k')

# specify X and Y axis limits
plt.xlim([6000, 9500])
plt.ylim([268.0, 271.5])

# 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=5,
                             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="Output from regline",
                             xlabel="simulation time",
                             ylabel="Surface temperature")

# Show the plot
plt.tight_layout()
plt.show()
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,
                          color='red',
                          label='first')
        axs[row][col].bar(x - width / 2,
                          data[panel][1][:],
Exemple #7
0
npts = 50
random = np.random.default_rng(seed=1)
data = random.chisquare(2.0, npts)

###############################################################################
# Plot

fig = plt.figure(figsize=(8, 8))
ax = plt.axes()

plt.plot(data, marker='o', linewidth=0, color='darkblue')

# Use geocat.viz.util convenience function to set axes parameters
gvutil.set_axes_limits_and_ticks(ax,
                                 xlim=(0, 50),
                                 ylim=(0, 10),
                                 xticks=range(0, 51, 10),
                                 yticks=range(0, 11, 2))

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

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

plt.show()
                    ax=ax,
                    orientation="horizontal",
                    aspect=30,
                    drawedges=True)
cbar.set_ticks(np.arange(262, 304, 4))

# 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,
                             maintitle="Ocean Only",
                             lefttitle=ocean_only.attrs['long_name'],
                             lefttitlefontsize=14,
                             righttitle=ocean_only.attrs['units'],
                             righttitlefontsize=14)

# Show the plot
plt.show()

###############################################################################
# Plot Land Only:

# Generate figure (set its size (width, height) in inches)
plt.figure(figsize=(10, 6))

# Generate axes using Cartopy and draw coastlines
ax = plt.axes(projection=projection)
ax.coastlines(linewidth=0.5, resolution="110m")
                                 xlim=(0, 49),
                                 ylim=(0, 29),
                                 xticks=np.linspace(0, 40, 5),
                                 yticks=np.linspace(0, 25, 6))

# 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=5,
                             labelsize=16)

# Use geocat.viz.util convenience function to add titles to left and right of the plot axis.
gvutil.set_titles_and_labels(ax,
                             lefttitle="Cone amplitude",
                             lefttitlefontsize=18,
                             righttitle="ndim",
                             righttitlefontsize=18,
                             xlabel="X",
                             ylabel="Y",
                             labelfontsize=18)

plt.show()

###############################################################################
# Plot With Enhancements:

# Make this figure the thumbnail image on the HTML page.
# sphinx_gallery_thumbnail_number = 2

#create figure
plt.figure(figsize=(10, 10))
Exemple #10
0
    vmax=10,
    levels=[-12, -10, -8, -6, -4, -2, -1, 1, 2, 4, 6, 8, 10, 12],
    cmap=newcmp,
    add_colorbar=False,
    transform=projection,
    add_labels=False)

# Add horizontal colorbar
cbar = plt.colorbar(p, orientation='horizontal', shrink=0.5)
cbar.ax.tick_params(labelsize=11)
cbar.set_ticks([-12, -10, -8, -6, -4, -2, -1, 1, 2, 4, 6, 8, 10, 12])

# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(ax,
                                 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(ax)

# 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='Anomalies: Surface Temperature',
                             righttitle='K')

# Show the plot
plt.show()
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,
                             x_minor_per_major=3,
                             y_minor_per_major=3,
                             labelsize=10)

gvutil.set_titles_and_labels(ax,
                             maintitle=olr.long_name,
                             maintitlefontsize=14,
                             lefttitle='degC',
                             lefttitlefontsize=12,
                             righttitle='(W m s$^{-2}$)',
                             righttitlefontsize=12)
# Add center title
ax.text(0.35, 1.06, 'December 1982', fontsize=12, transform=ax.transAxes)

# Add lower text box
ax.text(1,
        -0.2,
        "CONTOUR FROM -80 TO 40 BY 10",
        horizontalalignment='right',
        transform=ax.transAxes,
        bbox=dict(boxstyle='square, pad=0.25',
                  facecolor='white',
                  edgecolor='black'))
        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()
def plot_labelled_filled_contours(data, ax=None, label=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
        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 and make them semitransparent for plot legibility
    ax.coastlines(linewidth=0.5, alpha=0.75)

    # Use geocat.viz.util convenience function to set axes tick values
    gvutil.set_axes_limits_and_ticks(ax,
                                     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(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 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 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)

    # Add a label in the upper left of the axes
    ax.text(0.025,
            0.9,
            label,
            transform=ax.transAxes,
            bbox=dict(boxstyle='square, pad=0.25', facecolor='white'))
    return handles
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',
                             lefttitlefontsize=10,
                             righttitle=U.units,
                             righttitlefontsize=10)

# Load in colormap
newcmap = gvcmaps.gui_default

# Specify contour levels and contour ticks
speed_levels = np.arange(0, 40, 2.5)
speed_ticks = np.arange(2.5, 37.5, 2.5)
wind_levels = np.arange(-16, 44, 4)
Exemple #15
0
                                 xticks=np.linspace(-180, 180, 13),
                                 yticks=np.linspace(-60, 60, 5))

# Use geocat.viz.util convenience function to make latitude, longitude tick labels
gvutil.add_lat_lon_ticklabels(ax)
# Removing degree symbol from tick labels to more closely resemble NCL example
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 add titles
gvutil.set_titles_and_labels(ax,
                             lefttitle=temp.long_name,
                             righttitle=temp.units,
                             lefttitlefontsize=14,
                             righttitlefontsize=14)

# Add lower text box
ax.text(1,
        -0.15,
        "CONTOUR FROM -5 TO 30 BY 5",
        horizontalalignment='right',
        transform=ax.transAxes,
        bbox=dict(boxstyle='square, pad=0.25',
                  facecolor='white',
                  edgecolor='black'))

# Specify which contour levels to draw
contour_lev = np.arange(-5, 35, 5)
plt.figure(figsize=(6, 6))
ax = plt.gca()

# Plot original data
# Note that the s parameter sets the size of the markers in pts
plt.scatter(x, y, color='red', s=4)

# Plot regression
plt.plot(x_regress, y_regress, color='black', linewidth=0.5)

# specify X and Y axis limits
plt.xlim([6000, 9000])
plt.ylim([266, 274])

# Use geocat.viz utility functions to add a main title
gvutil.set_titles_and_labels(ax=ax, maintitle="Regression 1")

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

# Use geocat.viz.util convenience function to set axes parameters
gvutil.set_axes_limits_and_ticks(ax,
                                 xlim=(6000, 9000),
                                 xticks=np.arange(6000, 9001, 500),
                                 ylim=(266, 274),
                                 yticks=np.arange(266, 275, 2))

# Show plot
Exemple #17
0
cbar.ax.set_yticklabels([str(i) for i in np.arange(0, 32, 2)])

# 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(ax,
                                 xlim=(30, 120),
                                 ylim=(-60, 30),
                                 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(ax)

# 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="30-degree major and 10-degree minor ticks",
    maintitlefontsize=16,
    lefttitle="Potential Temperature",
    lefttitlefontsize=14,
    righttitle="Celsius",
    righttitlefontsize=14,
    xlabel="",
    ylabel="")

# Show the plot
plt.show()
# 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, x_minor_per_major=3, y_minor_per_major=5,
                             labelsize=12)

# Remove ticks on right side
ax.tick_params(which='both', right=False)

# Use geocat.viz.util convenience function to add title
gvutil.set_titles_and_labels(ax, maintitle="Explanation of Python contour levels")

# Create labels by colorbar
size = 8
y = 1 / num_lev / 2  # Offset from x axis in axes coordinates
ax.text(0.949, y, 'T < 248', fontsize=size, horizontalalignment='center',
        verticalalignment='center', transform=ax.transAxes,
        bbox=dict(boxstyle='square, pad=0.25',
                  facecolor='papayawhip',
                  edgecolor='papayawhip'))
text = '{} <= T < {}'
for i in range(0, 14):
    y = y + 1 / num_lev  # Vertical spacing between the labels
    ax.text(0.904, y, text.format(cbar_ticks[i], cbar_ticks[i + 1]),
            fontsize=size, horizontalalignment='center',
            verticalalignment='center', transform=ax.transAxes,
# labels
gvutil.add_lat_lon_ticklabels(ax)
# Removing degree symbol from tick labels to more closely resemble NCL example
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,
                             x_minor_per_major=4,
                             y_minor_per_major=5,
                             labelsize=12)

# Use geocat.viz.util convenience function to add titles
gvutil.set_titles_and_labels(
    ax,
    maintitlefontsize=16,
    maintitle=
    "Dummy station data colored and\nsized according to range of values")

# Plot markers with values less than first bin value
masked_lon = np.where(r < bins[0], lon, np.nan)
masked_lat = np.where(r < bins[0], lat, np.nan)
label = "x < " + str(bins[0])
plt.scatter(masked_lon,
            masked_lat,
            label=label,
            s=sizes[0],
            color=colors[0],
            zorder=1)

# Plot all other markers but those in the last bin
Exemple #20
0
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()

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

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

# Plot data with custom line characterisitcs
# Use keyword `color` to change the line color
# Use keyword `linewidth` to change the line thickness
# Use keyword `dashes` to create a custom dash pattern
                verticalalignment='center',
                transform=ccrs.Geodetic())

# Contour-plot U-data
p = wrap_U.plot.contour(ax=ax,
                        vmin=-8,
                        vmax=16,
                        transform=ccrs.PlateCarree(),
                        levels=np.arange(-12, 44, 4),
                        linewidths=0.5,
                        cmap='black',
                        add_labels=False)

ax.clabel(p, np.arange(-8, 17, 8), fmt='%d', inline=1, fontsize=14)

# Use geocat.viz.util convenience function to add left and right titles
gvutil.set_titles_and_labels(ax, lefttitle="Zonal Wind", righttitle="m/s")

# Add lower text box
ax.text(1.0,
        -.10,
        "CONTOUR FROM -12 TO 40 BY 4",
        horizontalalignment='right',
        transform=ax.transAxes,
        bbox=dict(boxstyle='square, pad=0.25',
                  facecolor='white',
                  edgecolor='black'))

# Show the plot
plt.show()
Exemple #22
0
             '4',
             labelpos='N',
             color='black',
             coordinates='axes',
             fontproperties={'size': 14},
             labelsep=0.1)

# Use geocat.viz.util convenience function to set axes tick values
gvutil.set_axes_limits_and_ticks(ax,
                                 xlim=(65, 95),
                                 ylim=(5, 25),
                                 xticks=range(70, 95, 10),
                                 yticks=range(5, 27, 5))

# 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=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 add titles to left and right of the plot axis.
gvutil.set_titles_and_labels(ax,
                             lefttitle='Sea Surface Temperature',
                             righttitle='C')

# Show the plot
plt.show()
ax.set_global()
ax.coastlines(linewidths=0.5)

# Plot data and add a colorbar
temp = wrap_t.plot.contourf(
    ax=ax,
    transform=ccrs.PlateCarree(),
    levels=11,
    cmap='coolwarm',
    add_colorbar=False)

cbar_ticks = np.arange(210, 311, 10)
cbar = plt.colorbar(temp, 
                    orientation='horizontal', 
                    shrink=0.75, 
                    pad=0.05, 
                    extendrect=True,
                    ticks=cbar_ticks)

cbar.ax.tick_params(labelsize=10)

# Use geocat.viz.util convenience function to add titles to left and right
# of the plot axis.
gvutil.set_titles_and_labels(ax,
                             maintitle="Example of Orthogonal Projection",
                             lefttitle="Surface Temperature",
                             righttitle="K")

# Show the plot
plt.show()
        patch = mpatches.Polygon(shape.points,
                                 facecolor=color,
                                 edgecolor='black',
                                 linewidth=0.5,
                                 transform=ccrs.PlateCarree(),
                                 zorder=2)
        ax.add_patch(patch)

# Create colorbar
plt.colorbar(cm.ScalarMappable(cmap=colormap, norm=norm),
             ax=ax,
             boundaries=colorbounds,
             orientation='horizontal',
             shrink=0.75,
             ticks=[1, 2, 3, 4],
             label='percent',
             aspect=30,
             pad=0.075)

# Add latitude and longitude labels
gl = ax.gridlines(draw_labels=True, x_inline=False, y_inline=False)
gl.xlocator = mticker.FixedLocator(np.linspace(-120, -80, 5))
gl.ylocator = mticker.FixedLocator(np.linspace(25, 45, 5))
gl.xlabel_style = {'rotation': 0}
gl.ylabel_style = {'rotation': 0}

# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax, maintitle='Percentage unemployment, by state')

plt.show()
Exemple #25
0
###############################################################################
# Plot

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

# Create a list of colors based on the color bar values
colors = ['red' if (value > 0) else 'blue' for value in dsoik[::8]]
plt.bar(date_frac[::8], dsoik[::8], align='edge', edgecolor='black',
        color=colors, width=8/12, linewidth=.6)

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

# Use geocat.viz.util convenience function to set axes parameters
gvutil.set_axes_limits_and_ticks(ax, ylim=(-3, 3),
                                 yticks=np.linspace(-3, 3, 7),
                                 yticklabels=np.linspace(-3, 3, 7),
                                 xlim=(date_frac[40], date_frac[-16]),
                                 xticks=np.linspace(1900, 1980, 5))

# Use geocat.viz.util convenience function to set titles and labels
gvutil.set_titles_and_labels(ax, maintitle="Darwin Southern Oscillation Index",
                             ylabel='Anomalies', maintitlefontsize=28,
                             labelfontsize=20)

plt.show()