Example #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)
Example #2
0
def map_close_up(ax):
    ax=map_china(ax)
    ax.set_extent([70,140,25,60], crs=ccrs.PlateCarree())
    ax.set_xticks([70,80,90,100,110,120,130, 140], crs=ccrs.PlateCarree())
    ax.set_yticks([25,30,35,40,45,50,55, 60], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
Example #3
0
def map_large_scale(ax):
    ax.set_extent([0,180,0,90], crs=ccrs.PlateCarree())
    ax.set_xticks([0,20,40,60,80,100,120,140,160,180], crs=ccrs.PlateCarree())
    ax.set_yticks([0,30,60,90], crs=ccrs.PlateCarree())
    lon_formatter = LongitudeFormatter(zero_direction_label=True, auto_hide=False)
    lat_formatter = LatitudeFormatter(auto_hide=False)
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.yaxis.set_minor_locator(  AutoMinorLocator(3))
    ax.xaxis.set_minor_locator(  AutoMinorLocator(2))
    ax.coastlines()
Example #4
0
def plot_german_data(lon,
                     lat,
                     adata,
                     pos=[],
                     plottitle='',
                     mycmap='RdBu_r',
                     axlims=[]):
    """
    plot map of annual mean temperature

    Parameters
    ----------
    lon : 2D array of longitude
    lat : 2D array of latitute
    adata : 2D array of temperature
    pos : position for a single marker, optional
    plottitle : title of figure, optional
    mycmap : colormap, optional
    axlims : 1x2 array of colobar axis limits, optional

    Returns
    -------
    fig : figure handle

    """
    states_provinces = cfeature.NaturalEarthFeature(category='cultural',
                                                    name='admin_0_countries',
                                                    scale='10m',
                                                    facecolor='none')
    fig = plt.figure(figsize=[10.5, 8])
    ax = plt.subplot(projection=ccrs.PlateCarree())
    da = plt.scatter(lon, lat, c=adata, marker='.', cmap=mycmap)
    ax.add_feature(states_provinces, edgecolor='gray')
    ax.set_aspect('equal', 'box')
    if len(pos) != 0:
        plt.plot(pos[1], pos[0], marker="o")
    if len(plottitle) != 0:
        ax.set_title(plottitle, fontsize=12)
    lonLabels = np.arange(0, 18, 3)
    latLabels = np.arange(45, 60, 3)
    gl = ax.gridlines(draw_labels=True, color='k', linewidth=1.5)
    gl.xlocator = mticker.FixedLocator(lonLabels)
    gl.ylocator = mticker.FixedLocator(latLabels)
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()
    cbar = plt.colorbar(da, pad=0.07)
    cbar.set_label('°C', rotation=90)
    if len(axlims) != 0:
        da.set_clim(axlims)
    plt.show()
    return fig
Example #5
0
ax.coastlines(linewidths=0.5, alpha=0.6)

# Use geocat.viz.util convenience function to set axes limits & tick values
gvutil.set_axes_limits_and_ticks(ax,
                                 xlim=(-180, 180),
                                 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 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 titles
gvutil.set_titles_and_labels(ax,
                             lefttitle=V.long_name,
                             righttitle=V.units,
                             lefttitlefontsize=12,
                             righttitlefontsize=12)

# Import an NCL colormap
cmap = gvcmaps.wgne15

# Specify which contour levels to draw
contour_lev = np.arange(-20, 28, 4)
# Plot filled contour
Example #6
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()
Example #7
0
def plot_regression(varin,lon,lat,cint=[0],ax=None,bbox=[-90,40,0,80],latlonlab=True,cbar=True,cbloc='horizontal'):
    """
    # Create regression plots for NAO and related EOFs (SLP)
    
    Inputs
        1) N (int) - PC index
        2) e (int) - ensemble index
        3) m (int) - month index
        4) varin (array: ens x mon x lat x lon x pc) - Regression Pattern
        5) lon (array: lon) - longitudes
        6) lat (array: lat) - latitudes
        7) varexp (array: ens x mon x pc) - Variance explained
    
        -OPTIONAL-
        8) cint (array: levels) - contour intervals
        9) ax (geoaxes object) - axis to plot on
        10) bbox (array: lonW,lonE,latS,latN) - plot extent
        11) latlonlab (bool) - True to include lat/lon labels
        12) cbar (bool) - True to include colorbar
    
    
    """

    # Get current axis if none is assigned
    if ax is None:
        ax = plt.gca()
    

    # Set colormap
    cmap = cmocean.cm.balance
    cmap.set_under(color='yellow')
    
    #Set Plotting boundaries
    ax.set_extent(bbox)
    
    # Add cyclic point to remove blank meridian
    var1,lon1 = add_cyclic_point(varin,lon) 
    
    # Add filled coastline
    ax.add_feature(cfeature.COASTLINE,linewidth=0.75,linestyle=":")
    
    # Add contours
    if len(cint) == 1:
        
        # Plot without specificing range
        cs = ax.contourf(lon1,lat,var1,cmap=cmap,extend="both",transform=ccrs.PlateCarree())
        
    else:
        
        
        cs = ax.contourf(lon1,lat,var1,cint,cmap=cmap,extend="both",transform=ccrs.PlateCarree())
        
        # Negative contours
        cln = ax.contour(lon1,lat,var1,
                    cint[cint<0],
                    linestyles='dashed',
                    colors='k',
                    linewidths=1,
                    transform=ccrs.PlateCarree())
        
        # Positive Contours
        clp = ax.contour(lon1,lat,var1,
                    cint[cint>=0],
                    colors='k',
                    linewidths=1,
                    transform=ccrs.PlateCarree())   
        # Add Label
        plt.clabel(cln,fmt='%.1f',fontsize=8)
        plt.clabel(clp,fmt='%.1f',fontsize=8)
    
    # Add Gridlines
    gl = ax.gridlines(draw_labels=True,linewidth=0.5,color='black',linestyle=':')
    if latlonlab is True:
        gl.top_labels = gl.right_labels = False
        gl.xformatter = LongitudeFormatter(degree_symbol='')
        gl.yformatter = LatitudeFormatter(degree_symbol='')
    else:
        gl.top_labels = gl.right_labels = gl.left_labels = gl_bottom_labels=False
    
    # Create colorbar
    if cbar == True:
        plt.colorbar(cs,ax=ax,fraction=0.046,pad=0.10,orientation=cbloc)
        
    #ax.set_title("PC%i Regression ENS %s Mon%i \n Variance Explained: %03d" %(N+1,estring,m+1,varexp*100)+r"%",fontsize=16)

    return ax
Example #8
0
ds = (snm2 - snm1) * filter_coeff
# Love numbers
kn = pgfl.LoveNumbers(deg_max)
# Legendre functions
lf = pgfl.LegendreFunctions(deg_max)

if __name__ == '__main__':
    # calculations
    w = ewh_calc()
    # Plot of result
    fig = plt.figure(figsize=[15, 8])
    ax = plt.subplot(projection=ccrs.PlateCarree())
    imgextend = [-180, 180, -90, 90]
    t = ax.imshow(w,
                  origin='upper',
                  extent=imgextend,
                  transform=ccrs.PlateCarree(),
                  cmap='RdBu')
    ax.coastlines('110m')  # 50m is also available
    lonLabels = np.arange(-180, 181, 60)
    latLabels = np.arange(-90, 91, 30)
    gl = ax.gridlines(draw_labels=True, color='k', linewidth=1.5)
    gl.xlocator = mticker.FixedLocator(lonLabels)
    gl.ylocator = mticker.FixedLocator(latLabels)
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()

    cbar = plt.colorbar(t)
    cbar.set_label('EWH / m', rotation=90)
    plt.show()
Example #9
0
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