def main():
    fig = plt.figure(figsize=[10, 5])
    ax1 = fig.add_subplot(1, 2, 1, projection=ccrs.SouthPolarStereo())
    ax2 = fig.add_subplot(1, 2, 2, projection=ccrs.SouthPolarStereo(),
                          sharex=ax1, sharey=ax1)
    fig.subplots_adjust(bottom=0.05, top=0.95,
                        left=0.04, right=0.95, wspace=0.02)

    # Limit the map to -60 degrees latitude and below.
    ax1.set_extent([-180, 180, -90, -60], ccrs.PlateCarree())

    ax1.add_feature(cfeature.LAND)
    ax1.add_feature(cfeature.OCEAN)

    ax1.gridlines()
    ax2.gridlines()

    ax2.add_feature(cfeature.LAND)
    ax2.add_feature(cfeature.OCEAN)

    # Compute a circle in axes coordinates, which we can use as a boundary
    # for the map. We can pan/zoom as much as we like - the boundary will be
    # permanently circular.
    theta = np.linspace(0, 2*np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax2.set_boundary(circle, transform=ax2.transAxes)

    plt.show()
예제 #2
0
def plot_SH_differences(case_array1, case_array2, times, variable_list,
                        highlat):

    grid = xr.open_dataset(
        '/glade/work/vcooper/grid_ref/sithick_SImon_CESM2_piControl_r1i1p1f1_gn_110001-120012.nc'
    )

    case_array1.TLAT[:] = grid.lat
    case_array1.TLON[:] = grid.lon
    case_array2.TLAT[:] = grid.lat
    case_array2.TLON[:] = grid.lon

    theta = np.linspace(0, 2 * np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpl.path.Path(verts * radius + center)

    for var in variable_list:
        fig = plt.figure(figsize=(18, 8))
        ax1 = plt.subplot(1, 3, 1, projection=ccrs.SouthPolarStereo())
        ax1.set_extent([-180, 180, -90, -highlat], ccrs.PlateCarree())
        ax1.gridlines()
        ax1.coastlines()
        ax1.set_boundary(circle, transform=ax1.transAxes)
        ax1.add_feature(cfeature.LAND, zorder=6)
        case_array1[var][(times[0] * 12 - 1), :, :].where(
            case_array1.TLAT < -30).plot.pcolormesh(
                'TLON', 'TLAT', ax=ax1, transform=ccrs.PlateCarree())

        ax2 = plt.subplot(1, 3, 2, projection=ccrs.SouthPolarStereo())
        ax2.set_extent([-180, 180, -90, -highlat], ccrs.PlateCarree())
        ax2.gridlines()
        ax2.coastlines()
        ax2.set_boundary(circle, transform=ax2.transAxes)
        ax2.add_feature(cfeature.LAND, zorder=6)
        case_array2[var][(times[1] * 12 - 1), :, :].where(
            case_array2.TLAT < -30).plot.pcolormesh(
                'TLON', 'TLAT', ax=ax2, transform=ccrs.PlateCarree())

        ax3 = plt.subplot(1, 3, 3, projection=ccrs.SouthPolarStereo())
        ax3.set_extent([-180, 180, -90, -highlat], ccrs.PlateCarree())
        ax3.gridlines()
        ax3.coastlines()
        ax3.set_boundary(circle, transform=ax3.transAxes)
        ax3.add_feature(cfeature.LAND, zorder=6)
        diff = case_array2[var][(times[1] * 12 - 1), :, :].where(
            case_array1.TLAT < -30) - case_array1[var][
                (times[0] * 12 - 1), :, :].where(case_array1.TLAT < -30)

        diff.plot.pcolormesh('TLON',
                             'TLAT',
                             ax=ax3,
                             transform=ccrs.PlateCarree(),
                             cmap='RdBu_r')
        ax3.set_title('$\Delta$' + var)

        plt.show()
        plt.tight_layout()
예제 #3
0
def interp_to_latlon(data2d, lat, lon, lat_i, lon_i):
    """
    # interpolating in lat/lon space has issues. interpolate in
    # stereographic projection:
    #
    # input:
    #    unstructured 1D data:  data(ncol),lat(ncol),lon(ncol)
    #    target lat/lon grid:   lon_i(nlon), lat_i(nlat)
    #
    # output 2D interpolated data::
    #   data(nlon,nlat)
    #
    """
    # mesh grid
    dproj = ccrs.PlateCarree()
    nhalf = int(len(lat_i) / 2)
    lat_south = lat_i[:nhalf]
    lat_north = lat_i[nhalf:]

    # take source data in the correct hemisphere, include extra halo points for interpolation
    # using the full global data sometimes confuses griddata with points being mapped close to infinity
    halo = 15  # degrees
    data2d_h = data2d[lat < halo]

    lon_h = lon[lat < halo]
    lat_h = lat[lat < halo]
    xv, yv = numpy.meshgrid(lon_i, lat_south)
    coords_in = ccrs.SouthPolarStereo().transform_points(dproj, lon_h, lat_h)
    coords_out = ccrs.SouthPolarStereo().transform_points(
        dproj, xv.flatten(), yv.flatten())
    data_s = griddata(coords_in[:, 0:2],
                      data2d_h,
                      coords_out[:, 0:2],
                      method='linear')

    data2d_h = data2d[lat > -halo]
    lon_h = lon[lat > -halo]
    lat_h = lat[lat > -halo]
    xv, yv = numpy.meshgrid(lon_i, lat_north)
    coords_in = ccrs.NorthPolarStereo().transform_points(dproj, lon_h, lat_h)
    coords_out = ccrs.NorthPolarStereo().transform_points(
        dproj, xv.flatten(), yv.flatten())
    data_n = griddata(coords_in[:, 0:2],
                      data2d_h,
                      coords_out[:, 0:2],
                      method='linear')

    data_i = numpy.concatenate(
        (data_s, data_n)).reshape(len(lat_i), len(lon_i))
    return data_i
예제 #4
0
    def Setup_CaratoPy_Map(self,Projection,xs,ys,ns):
        import pylab as pl
        import numpy as np
        import cartopy.crs as ccrs
        import matplotlib.path as mpath

        if Projection=="PC":
            ax = pl.subplot(xs,ys,ns,projection=ccrs.PlateCarree())
            ax.gridlines(crs=ccrs.PlateCarree(),linewidth=0.2)
            ax.set_xticks(np.linspace(-180,180,13), minor=False, crs=None)
            ax.set_yticks(np.linspace(-90,90,7), minor=False, crs=None)
            ax.tick_params(axis='both', which='major', labelsize=7)
            pl.ylabel("Latitude (deg)",fontsize=7)
            pl.xlabel("Longitude (deg)",fontsize=7)
        else:
            if Projection=="NP":
                ax = pl.subplot(xs,ys,ns,projection=ccrs.NorthPolarStereo())
                ax.set_extent([-180, 180, 0, 90], crs=ccrs.PlateCarree())
            elif Projection=="SP":
                ax = pl.subplot(xs,ys,ns,projection=ccrs.SouthPolarStereo())
                ax.set_extent([-180, 180, -90, 0], crs=ccrs.PlateCarree())
            ax.gridlines(crs=ccrs.PlateCarree(),linewidth=0.2)
            ax.set_xticks(np.linspace(-180,180,13), minor=False, crs=None)
            ax.set_yticks(np.linspace(-90,90,7), minor=False, crs=None)
            ax.tick_params(axis='both', which='major', labelsize=7)
            theta = np.linspace(0, 2*np.pi, 100)
            center, radius = [0.5, 0.5], 0.5
            verts = np.vstack([np.sin(theta), np.cos(theta)]).T
            circle = mpath.Path(verts * radius + center)
            ax.set_boundary(circle, transform=ax.transAxes)

        #IN THE FUTURE SHOULD MAKE THESE CONFIGURATION FILE FIELDS
        pl.title(self.ID,fontsize=9)
        
        return 0
    def _get_ccrs(self):
            """
            given the projection and the domain, returns
            the cartopy projection of the map (the data projection, i.e.
            the 'transform' argument, is always assumed to be
            ccrs.PlateCarree(central_longitude=0))
            """

            if not(self.proj):
                self.proj = 'cyl'
                self.crs = ccrs.PlateCarree(central_longitude=0)

            if self.proj in ['cyl', 'merc']:
                self.crs = ccrs.PlateCarree(central_longitude=180)

            if self.proj == 'moll':
                self.crs = ccrs.Mollweide(central_longitude=180)

            if self.proj == 'spstere':
                self.crs = ccrs.SouthPolarStereo(central_longitude=180)

            if self.proj == 'npstere':
                self.crs = ccrs.NorthPolarStereo(central_longitude=180)

            return self
예제 #6
0
 def polar_bluemarble():
     source_proj = ccrs.SouthPolarStereo()
     source_proj._max = 5e6
     fname = '/home/h02/itpe/foo.png'
     img_origin = 'lower'
     img = plt.imread(fname)
     return img, img_origin, source_proj
예제 #7
0
    def make_map(self):
        #set basemap
        try: self.fig.delaxes(self.ax)
        except AttributeError: self.parent.user_warning("Unable to remove previous axis and refresh map, raise issue with Dev.")
        #TODO: ADD TRANSVERSE MERCATOR AT STRIKE AS OPTION
        if self.proj_box.GetValue() == 'North Polar Stereographic':
            self.proj = ccrs.NorthPolarStereo(central_longitude=self.center_lon,true_scale_latitude=None,globe=None)
            self.ax = self.fig.add_subplot(111,projection=self.proj)
#            pgeo.make_circular_ax(self.ax)
        elif self.proj_box.GetValue() == 'South Polar Stereographic':
            self.proj = ccrs.SouthPolarStereo(central_longitude=self.center_lon,true_scale_latitude=None,globe=None)
            self.ax = self.fig.add_subplot(111,projection=self.proj)
#            pgeo.make_circular_ax(self.ax)
        elif self.proj_box.GetValue() == 'Orthographic':
            self.proj = ccrs.Orthographic(central_longitude=self.center_lon)
            self.ax = self.fig.add_subplot(111,projection=self.proj)
        else: self.parent.user_warning("Projection %s not supported"%str(self.proj_box.GetValue())); return

#        self.ax.set_xticks(np.arange(0, 370, 10.), crs=ccrs.PlateCarree())
#        self.ax.set_yticks(np.arange(-80, 90, 10.), crs=ccrs.PlateCarree())
#        self.ax.tick_params(grid_linewidth=.5,grid_linestyle=":",color="k",labelsize=8)
#        lon_formatter = LongitudeFormatter(zero_direction_label=True)
#        lat_formatter = LatitudeFormatter()
#        self.ax.xaxis.set_major_formatter(lon_formatter)
#        self.ax.yaxis.set_major_formatter(lat_formatter)
        self.ax.gridlines(color='grey', alpha=0.5, linestyle='--',linewidth=.5)
        land = cfeature.NaturalEarthFeature('physical', 'land', self.resolution, edgecolor="black", facecolor="grey", linewidth=2)
        self.ax.add_feature(land)
예제 #8
0
def plot_transect_map(lon_start, lat_start, lon_end, lat_end, 
                      mesh, npoints=30, view = 'w', stock_img=False):
    # plt.figure(figsize=(10,10))
    lonlat = transect_get_lonlat(lon_start, lat_start, lon_end, lat_end, npoints=npoints)
    nodes  = transect_get_nodes(lonlat, mesh)
    dist   = transect_get_distance(lonlat)

    if view=='w':
        ax = plt.subplot(111, projection=ccrs.Mercator(central_longitude=0))
        ax.set_extent([180, -180, -80, 90], crs=ccrs.PlateCarree())
    elif view=='np':
        ax = plt.subplot(111, projection=ccrs.NorthPolarStereo(central_longitude=0))
        ax.set_extent([180, -180, 60, 90], crs=ccrs.PlateCarree())
    elif view=='sp':
        ax = plt.subplot(111, projection=ccrs.SouthPolarStereo(central_longitude=0))
        ax.set_extent([180, -180, -90, -50], crs=ccrs.PlateCarree())
    else:
        raise ValueError('The "{}" is not recognized as valid view option.'.format(view))
    
    
    ax.scatter(lonlat[:,0], lonlat[:,1], s=30, c='b',  transform=ccrs.PlateCarree())
    ax.scatter(mesh.x2[nodes], mesh.y2[nodes], s=30, c='r',  transform=ccrs.PlateCarree())
    if stock_img==True:
        ax.stock_img()
    ax.coastlines(resolution='50m')
    return ax
예제 #9
0
def plot_scalar_field(lons, lats, data, grid_type):
    import matplotlib.pyplot as plt
    import cartopy
    import cartopy.crs as ccrs

    if grid_type == 'latlon':
        ax = plt.axes(projection=ccrs.SouthPolarStereo())

        land_50m = cartopy.feature.NaturalEarthFeature('physical',
                                                       'land',
                                                       '50m',
                                                       edgecolor='face',
                                                       facecolor='dimgray',
                                                       linewidth=0)
        ax.add_feature(land_50m)
        ax.set_extent([-180, 180, -90, -50], ccrs.PlateCarree())

        vector_crs = ccrs.PlateCarree()
        im = ax.pcolormesh(lons, lats, data, transform=vector_crs)

        plt.colorbar(im)
        plt.show()
    elif grid_type == 'polar_stereographic_xy' or grid_type == 'ease_rowcol':
        plt.pcolormesh(lons, lats, data)
        plt.gca().invert_yaxis()
        plt.colorbar()
        plt.show()
def plot_points_so(lons, lats, markersize):

    ax = plt.axes(projection=ccrs.SouthPolarStereo())

    # Limit the map to -60 degrees latitude and below.
    ax.set_extent([-180, 180, -90, -45], ccrs.PlateCarree())
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)

    ax.gridlines(crs=ccrs.PlateCarree(),
                 draw_labels=False,
                 linewidth=.5,
                 color='gray',
                 alpha=0.5,
                 linestyle='--')

    ax.coastlines('110m', linewidth=0.8)

    plt.scatter(lons,
                lats,
                marker='.',
                color='red',
                s=markersize,
                alpha=0.7,
                transform=ccrs.Geodetic())
def Antarctic_plot(xarray,subplot_val1,subplot_val2,subplot_val3):
    # basically makes a set of nice plots over the Antarctic given an xarray input and some idea of the position in a grid
    ax1 = plt.subplot(subplot_val1,subplot_val2,subplot_val3, projection=ccrs.SouthPolarStereo(central_longitude=-180))
          # plt,subplot(x1,x2,x3)
                    # x1: the number of rows about subplots
                    # x2: the number of columns about subplots
                    # x3: the index subplot in each row
          # ccrs.SouthPolarStereo : according to "Cartopy projection list"
                    #  link: #  https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html    
          # central longitude keyword puts New Zealand up rather than down on plot
    kw = dict( central_latitude=-90, central_longitude=180) 
    ax1.set_extent([12,84,60,90],ccrs.PlateCarree())
    # set the extent of plot [145E,215E,55S,80S]
    ax1.add_feature(cartopy.feature.LAND,zorder=0)#add feature--Land

    

    #get size and extent of axes:
    axpos = ax1.get_position()
    pos_x = axpos.x0 + axpos.width + 0.01 # + 0.25 * axpos.width
    pos_y = axpos.y0
    cax_width = 0.04
    cax_height = axpos.height
    cs = ax1.pcolormesh(xarray.longitude.values,xarray.latitude.values,xarray.variable.values,cmap='seismic', transform=ccrs.PlateCarree(),vmin=-8.0,vmax=8.0) 
      # draw a quadrilateral mesh
               #pcolormesh(x,y,Z,camp,vmin,vmax)
                   # camp:colormaps_reference.py; 
                          #link:  https://matplotlib.org/examples/color/colormaps_reference.html
                   #vmin; vmax: normalize luminance data   
                   
    ax1.coastlines()
    ax1.gridlines()
    return cs
예제 #12
0
def reduce_density(df,
                   dens,
                   south=-90,
                   north=90,
                   east=180,
                   west=-180,
                   projection='EU'):
    df_small = df[(df.latitude >= south) & (df.latitude <= north) &
                  (df.longitude <= east) & (df.longitude >= west)]
    if (projection == 'GR') or (projection == 'Arctic'):
        proj = ccrs.LambertConformal(central_longitude=-35,
                                     central_latitude=65,
                                     standard_parallels=[35])
    elif projection == 'Antarctica':
        proj = ccrs.SouthPolarStereo()
    # elif projection == 'Arctic':
    #     proj = ccrs.NorthPolarStereo()

    else:
        proj = ccrs.LambertConformal(central_longitude=13,
                                     central_latitude=47,
                                     standard_parallels=[35])
    # Use the cartopy map projection to transform station locations to the map
    # and then refine the number of stations plotted by setting a 300km radius
    point_locs = proj.transform_points(ccrs.PlateCarree(),
                                       df_small['longitude'].values,
                                       df_small['latitude'].values)
    df = df_small[reduce_point_density(point_locs, dens)]
    if projection == 'Arctic':
        proj = ccrs.NorthPolarStereo()

    return proj, point_locs, df
예제 #13
0
def create_cartopy_axes(ax=None, lw=0.5, c='k'):
    """
    USAGE:      xarray.DataArray2D.plot(**cartopy_axes_spstere())
    OUTPUT:     south polar steriographic plot
    REQUIRES:   xarray, cartopy
    """

    import cartopy.crs as ccrs
    import cartopy.feature
    import matplotlib.path as mpath
    import matplotlib.pyplot as plt
    import numpy as np

    if ax is None:
        ax = plt.axes(projection=ccrs.SouthPolarStereo())

    theta = np.linspace(0, 2 * np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)

    ax.add_feature(cartopy.feature.LAND, facecolor='#CCCCCC', zorder=5)
    ax.add_feature(cartopy.feature.COASTLINE, linewidth=lw, zorder=5)
    ax.add_feature(cartopy.feature.BORDERS, linewidth=lw)

    ca = dict(robust=True, ax=ax, transform=ccrs.PlateCarree())

    return ca
예제 #14
0
def main():

    plt.figure(figsize=[8, 8])
    ax = plt.axes(projection=ccrs.SouthPolarStereo())

    ax.coastlines()
    ax.gridlines()

    # Add a background image. Note: unlike the Robinson projection, the
    # background image spills outside the boundary due to the fact that
    # points outside the boundary have 1:1 mappings in this projection
    im = ax.stock_img()

    def on_draw(event=None):
        """
        Hooks into matplotlib's event mechanism to define the clip path of the
        background image.

        """
        # Clip the image to the current background boundary.
        im.set_clip_path(ax.background_patch.get_path(),
                         transform=ax.background_patch.get_transform())

    # Register the on_draw method and call it once now.
    plt.gcf().canvas.mpl_connect('draw_event', on_draw)
    on_draw()

    # Generate a matplotlib path representing the character "C"
    fp = FontProperties(family='Arial', weight='bold')
    logo_path = matplotlib.textpath.TextPath((-4.5e7, -3.7e7),
                                             'C',
                                             size=1,
                                             prop=fp)

    # Scale the letter up to an appropriate X and Y scale
    logo_path._vertices *= np.array([123500000, 103250000])

    # Add the path as a patch, drawing black outlines around the text
    patch = matplotlib.patches.PathPatch(logo_path,
                                         facecolor='white',
                                         edgecolor='black',
                                         linewidth=10,
                                         transform=ccrs.SouthPolarStereo())
    ax.add_patch(patch)

    plt.show()
예제 #15
0
    def make_map(self):
        #set basemap
        try:
            self.fig.delaxes(self.ax)
        except AttributeError:
            pass
        #TODO: ADD TRANSVERSE MERCATOR AT STRIKE AS OPTION
        if self.proj_box.GetValue() == 'North Polar Stereographic':
            self.proj = ccrs.NorthPolarStereo(
                central_longitude=self.center_lon,
                true_scale_latitude=None,
                globe=None)
            self.ax = self.fig.add_subplot(111, projection=self.proj)
            pgeo.make_circular_ax(self.ax)
        elif self.proj_box.GetValue() == 'South Polar Stereographic':
            self.proj = ccrs.SouthPolarStereo(
                central_longitude=self.center_lon,
                true_scale_latitude=None,
                globe=None)
            self.ax = self.fig.add_subplot(111, projection=self.proj)
            pgeo.make_circular_ax(self.ax)
        elif self.proj_box.GetValue() == 'Mercator':
            self.proj = ccrs.Mercator(central_longitude=self.center_lon)
            self.ax = self.fig.add_subplot(111, projection=self.proj)
            path = mpath.Path(
                np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]))
            self.ax.set_boundary(path, transform=self.ax.transAxes)
        elif self.proj_box.GetValue() == 'Mollweide':
            self.proj = ccrs.Mollweide(central_longitude=self.center_lon,
                                       globe=None)
            self.ax = self.fig.add_subplot(111, projection=self.proj)
#            path = mpath.Path(np.array([[0.05,0.05],[0.95,0.05],[0.95,0.95],[0.05,0.95],[0.05,0.05]]))
#            self.ax.set_boundary(path, transform=self.fig.transFigure)
        else:
            self.parent.user_warning("Projection %s not supported" %
                                     str(self.proj_box.GetValue()))
            return

        self.ax.set_xticks(np.arange(0, 370, 10.), crs=ccrs.PlateCarree())
        self.ax.set_yticks(np.arange(-80, 90, 10.), crs=ccrs.PlateCarree())
        self.ax.tick_params(grid_linewidth=.5,
                            grid_linestyle=":",
                            color="k",
                            labelsize=8)
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        self.ax.xaxis.set_major_formatter(lon_formatter)
        self.ax.yaxis.set_major_formatter(lat_formatter)
        #        self.ax.gridlines(color='grey', alpha=0.5, linestyle='--',linewidth=.5)
        land = cfeature.NaturalEarthFeature('physical',
                                            'land',
                                            '110m',
                                            edgecolor="black",
                                            facecolor="",
                                            linewidth=2)
        self.ax.add_feature(land)
예제 #16
0
def run_so_map() -> None:
    """Run through and plot."""
    sps.mpl_params()
    map_proj = ccrs.SouthPolarStereo()
    fig = plt.figure()
    ax = fig.add_subplot(111, projection=map_proj)
    mp.southern_ocean_axes_setup(ax, fig)
    draw_fronts_kim(ax)
    plt.legend()
    plt.savefig(os.path.join(cst.FIGURE_PATH, "ko.png"))
예제 #17
0
def plot_transect_map(lonlat, mesh, view="w", stock_img=False):
    """Plot map of the transect.
    
    Parameters
    ----------
    lonlat : np.array
        2 dimentional np. array that contains longitudea and latitudes.
        Can be constructed from vectors as lonlat = np.vstack((lon, lat))
    mesh: mesj object
    view: str
        Projection to use for the map:
        w - global (Mercator)
        np - North Polar Stereo
        sp - South Polar Stereo
    stock_imd: bool
        Show stock backgroung image. Usually makes things slower.
    
    Returns
    -------
    ax: cartopy axis object
    
    """

    nodes = transect_get_nodes(lonlat, mesh)

    if view == "w":
        ax = plt.subplot(111, projection=ccrs.Mercator(central_longitude=0))
        ax.set_extent([180, -180, -80, 90], crs=ccrs.PlateCarree())
    elif view == "np":
        ax = plt.subplot(111,
                         projection=ccrs.NorthPolarStereo(central_longitude=0))
        ax.set_extent([180, -180, 60, 90], crs=ccrs.PlateCarree())
    elif view == "sp":
        ax = plt.subplot(111,
                         projection=ccrs.SouthPolarStereo(central_longitude=0))
        ax.set_extent([180, -180, -90, -50], crs=ccrs.PlateCarree())
    else:
        raise ValueError(
            'The "{}" is not recognized as valid view option.'.format(view))

    ax.scatter(lonlat[0, :],
               lonlat[1, :],
               s=30,
               c="b",
               transform=ccrs.PlateCarree())
    ax.scatter(mesh.x2[nodes],
               mesh.y2[nodes],
               s=30,
               c="r",
               transform=ccrs.PlateCarree())
    if stock_img == True:
        ax.stock_img()
    ax.coastlines(resolution="50m")
    return ax
예제 #18
0
def main():
    fig = plt.figure(figsize=[8, 8])
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.SouthPolarStereo())

    ax.coastlines()
    ax.gridlines()

    im = ax.stock_img()

    def on_draw(event=None):
        """
        Hook into matplotlib's event mechanism to define the clip path of the
        background image.

        """
        # Clip the image to the current background boundary.
        im.set_clip_path(ax.background_patch.get_path(),
                         transform=ax.background_patch.get_transform())

    # Register the on_draw method and call it once now.
    fig.canvas.mpl_connect('draw_event', on_draw)
    on_draw()

    # Generate a matplotlib path representing the character "C".
    fp = FontProperties(family='Bitstream Vera Sans', weight='bold')
    logo_path = matplotlib.textpath.TextPath((-4.5e7, -3.7e7),
                                             'C',
                                             size=1,
                                             prop=fp)

    # Scale the letter up to an appropriate X and Y scale.
    logo_path._vertices *= np.array([103250000, 103250000])

    # Add the path as a patch, drawing black outlines around the text.
    patch = matplotlib.patches.PathPatch(logo_path,
                                         facecolor='white',
                                         edgecolor='black',
                                         linewidth=10,
                                         transform=ccrs.SouthPolarStereo())
    ax.add_patch(patch)
    plt.show()
예제 #19
0
    def __init__(self, nrows=1, ncols=1,
                 figsize=(12,10), background='black',
                 xr_cbar=False,
                 subplot_kw=None,
                 just_init_fig=False,
                 do_nothing=False,
                 **kwargs):
        """Create StereoPlot object

        Parameters
        ----------
        nrows, ncols : int, optional
            passed to matplotlib.pyplot.subplots
        figsize : tuple, optional
            passed to matplotlib.pyplot.subplots
        background : str or matplotlib colormap object
            sets the "bad_color" or background color
        xr_cbar : bool, optional
            use xarray's default colorbar, or not
        kwargs
            passed to matplotlib.pyplot.subplots
        """

        self.projection = ccrs.SouthPolarStereo(central_longitude=self.lon0)
        skw=subplot_kw if subplot_kw is not None else \
            {'projection':self.projection}
        if not do_nothing:
            if not just_init_fig:
                fig,axs = plt.subplots(nrows=nrows,ncols=ncols,
                                       figsize=figsize,
                                       subplot_kw=skw,
                                       **kwargs)
                if isinstance(axs,list):
                    axs = np.ndarray(axs)
                self.axs = axs
            else:
                fig = plt.figure(figsize=figsize)

            self.fig = fig

        if ncols*nrows>1:
            self.isSingle = False

        else:
            self.isSingle = True

        self.nrows=nrows
        self.ncols=ncols
        self.xr_cbar = xr_cbar
        self.background = background
        self.dLon = self.extent[ 1] - self.extent[ 0]
        self.dLat = self.extent[-1] - self.extent[-2]
예제 #20
0
def main():
    fig = plt.figure(figsize=[8, 8])
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.SouthPolarStereo())

    ax.coastlines()
    ax.gridlines()
    ax.stock_img()

    # Generate a matplotlib path representing the character "C".
    fp = FontProperties(family='Bitstream Vera Sans', weight='bold')
    logo_path = matplotlib.textpath.TextPath((-4.5e7, -3.7e7),
                                             'C', size=1, prop=fp)

    # Scale the letter up to an appropriate X and Y scale.
    logo_path._vertices *= np.array([103250000, 103250000])

    # Add the path as a patch, drawing black outlines around the text.
    patch = matplotlib.patches.PathPatch(logo_path, facecolor='white',
                                         edgecolor='black', linewidth=10,
                                         transform=ccrs.SouthPolarStereo())
    ax.add_patch(patch)
    plt.show()
예제 #21
0
def southpolarstereo(lat):
    # circle boundary
    theta = np.linspace(0, 2 * np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpl.path.Path(verts * radius + center)

    ax = plt.subplot(projection=ccrs.SouthPolarStereo())
    ax.set_extent([-180, 180, -90, -lat], ccrs.PlateCarree())
    ax.gridlines()
    ax.coastlines()
    ax.set_boundary(circle, transform=ax.transAxes)
    ax.add_feature(cfeature.LAND, zorder=6)
예제 #22
0
def plot_map_nsidc(data, date):
    plt.clf()
    polar_crs = ccrs.SouthPolarStereo()
    plain_crs = ccrs.PlateCarree()
    polar_extent = [-180, 180, -90, -60]
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(1, 1, 1, projection=polar_crs)
    ax.axis('off')
    ax.set_extent(polar_extent, crs=plain_crs)
    ax.coastlines(resolution='50m', color='k')
    ax.gridlines(linestyle='--', draw_labels=True)
    #test if the lat/lon grid is downloaded yet, if not then download:
    if os.path.isfile("pss25lons_v3.dat") * os.path.isfile(
            "pss25lats_v3.dat") == False:
        commands.getoutput(
            "wget ftp://sidads.colorado.edu/pub/DATASETS/seaice/polar-stereo/tools/pss25lats_v3.dat"
        )  #get the lat/lon grid from NSIDC
        commands.getoutput(
            "wget ftp://sidads.colorado.edu/pub/DATASETS/seaice/polar-stereo/tools/pss25lons_v3.dat"
        )  #get the lat/lon grid from NSIDC
        commands.getoutput(
            "wget ftp://sidads.colorado.edu/pub/DATASETS/seaice/polar-stereo/tools/pss25area_v3.dat"
        )  #get the lat/lon grid from NSIDC
    with open("pss25lons_v3.dat", "rb") as file:
        lons = np.fromfile(file, dtype=np.dtype("(332,316)i4"))[0]
        lons = np.rot90(lons, 2) / 100000.
    with open("pss25lats_v3.dat", "rb") as file:
        lats = np.fromfile(file, dtype=np.dtype("(332,316)i4"))[0]
        lats = np.rot90(lats, 2) / 100000.
    with open("pss25area_v3.dat", "rb") as file:
        areas = np.fromfile(file, dtype=np.dtype("(332,316)i4"))[0]
        areas = np.rot90(areas, 2) / 1000.
    data[lats > -61] = np.nan
    t = ax.pcolormesh(lons,
                      lats,
                      data,
                      transform=ccrs.PlateCarree(),
                      cmap='Blues_r')
    cbar = plt.colorbar(t,
                        orientation="horizontal",
                        fraction=.03,
                        aspect=46,
                        pad=.07)
    cbar.set_label("% ice cover")
    plt.title("Sea ice concentration on {}".format(date))
    theta = np.linspace(0, 2 * np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)
    ax.set_boundary(circle, transform=ax.transAxes)
    return ax
예제 #23
0
def plot(lat, lon, Z, date, time, intfactor, maxtec, aacgm, plottype, extent):

    tecmap = plt.figure(figsize=(11, 8))

    if plottype == 'Northern Hemisphere':
        map_proj = ccrs.NorthPolarStereo()
    elif plottype == 'Southern Hemisphere':
        map_proj = ccrs.SouthPolarStereo()
    elif plottype == 'Global':
        map_proj = ccrs.PlateCarree()
    if aacgm:
        ax = tecmap.add_subplot(projection='aacgmv2', map_projection=map_proj)
        ax.overaly_coast_lakes(coords="aacgmv2", plot_date=date)

        if map_proj == ccrs.PlateCarree():
            mesh = ax.pcolor(lon,
                             lat,
                             Z,
                             cmap='jet',
                             vmax=maxtec,
                             transform=ccrs.PlateCarree())
        else:
            mesh = ax.scatter(lon,
                              lat,
                              c=Z,
                              cmap='jet',
                              vmax=maxtec,
                              transform=ccrs.PlateCarree())

    else:
        #usepcolormesh in
        ax = plt.axes(projection=map_proj)
        ax.add_feature(cfeature.COASTLINE)
        ax.add_feature(cfeature.LAKES)
        mesh = ax.pcolormesh(lon,
                             lat,
                             Z,
                             cmap='jet',
                             vmax=maxtec,
                             transform=ccrs.PlateCarree())

    ax.set_extent(extent, ccrs.PlateCarree())
    clrbar = plt.colorbar(mesh, shrink=0.5)
    clrbar.set_label('Total Electron Content (TECU)')
    ax.gridlines(linewidth=0.5)
    plt.title('Total Electron Content for ' + str(date.month) + '/' +
              str(date.day) + '/' + str(date.year) + ' at ' + str(time.hour) +
              ':' + ('%02d' % time.minute) + ' UT')
    st.pyplot(tecmap)
def plot_field_contourf(xx,
                        yy,
                        data,
                        levels,
                        cmin,
                        cmax,
                        n_lat_lim=-45,
                        cmap='jet'):

    #fig = plt.figure(figsize=[7,7])
    ax = plt.axes(projection=ccrs.SouthPolarStereo())

    # Limit the map to -60 degrees latitude and below.
    ax.set_extent([-180, 180, -90, n_lat_lim], ccrs.PlateCarree())
    #ax.add_feature(cfeature.LAND)
    #ax.add_feature(cfeature.OCEAN)

    theta = np.linspace(0, 2 * np.pi, 100)
    center, radius = [0.5, 0.5], 0.5
    verts = np.vstack([np.sin(theta), np.cos(theta)]).T
    circle = mpath.Path(verts * radius + center)

    ax.set_boundary(circle, transform=ax.transAxes)

    ax.gridlines(crs=ccrs.PlateCarree(),
                 draw_labels=False,
                 linewidth=1,
                 color='black',
                 alpha=0.5,
                 linestyle='--')

    ease_crs = ccrs.epsg(6932)

    plt.contourf(xx,
                 yy,
                 data,
                 levels,
                 transform=ease_crs,
                 vmin=cmin,
                 vmax=cmax,
                 cmap=cmap)

    ax.add_feature(cfeature.LAND)

    ax.coastlines('110m', linewidth=0.8)

    #    ax.gridlines()
    plt.colorbar()
    plt.show()
예제 #25
0
def test_geoaxes_set_boundary_clipping():
    """Test that setting the boundary works properly for clipping #1620."""
    lon, lat = np.meshgrid(np.linspace(-180., 180., 361),
                           np.linspace(-90., -60., 31))
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1, projection=ccrs.SouthPolarStereo())

    # Limit the map to -60 degrees latitude and below.
    ax1.set_extent([-180, 180, -90, -60], ccrs.PlateCarree())
    ax1.gridlines()

    ax1.contourf(lon, lat, lat, transform=ccrs.PlateCarree())

    ax1.set_boundary(mpath.Path.circle(center=(0.5, 0.5), radius=0.5),
                     transform=ax1.transAxes)
예제 #26
0
def plot(reference, test, diff, metrics_dict, parameter):

    # Create figure, projection
    fig = plt.figure(figsize=[8.5, 11.0])

    # Create projection
    print parameter.var_region
    if parameter.var_region.find('N') !=-1:
        pole = 'N'
        proj = ccrs.NorthPolarStereo(central_longitude=0)
    elif parameter.var_region.find('S') !=-1:
        pole = 'S'
        proj = ccrs.SouthPolarStereo(central_longitude=0)

    # First two panels
    min1  = metrics_dict['test']['min']
    mean1 = metrics_dict['test']['mean']
    max1  = metrics_dict['test']['max']
    if test.count() >1: 
        plot_panel(0, fig, proj, pole, test, parameter.contour_levels, 'viridis', (parameter.test_name,parameter.test_title,test.units),stats=(max1,mean1,min1))

    min2  = metrics_dict['ref']['min']
    mean2 = metrics_dict['ref']['mean']
    max2  = metrics_dict['ref']['max']

    if reference.count() >1: 
        plot_panel(1, fig, proj, pole, reference, parameter.contour_levels, 'viridis', (parameter.reference_name,parameter.reference_title,reference.units),stats=(max2,mean2,min2))

    # Third panel
    min3  = metrics_dict['diff']['min']
    mean3 = metrics_dict['diff']['mean']
    max3  = metrics_dict['diff']['max']
    r = metrics_dict['misc']['rmse']
    c = metrics_dict['misc']['corr']

    if diff.count() >1: 
        plot_panel(2, fig, proj, pole, diff, parameter.diff_levels, 'RdBu_r', (None,parameter.diff_title,None), stats=(max3,mean3,min3,r,c))

    # Figure title
    fig.suptitle(parameter.main_title, x=0.5, y=0.97, fontsize=18)

    # Save figure
    for f in parameter.output_format:
        f = f.lower().split('.')[-1]
        fnm = os.path.join(get_output_dir('7', parameter), parameter.output_file)
        plt.savefig(fnm + '.' + f)
        print('Plot saved in: ' + fnm + '.' + f)
예제 #27
0
def test_multiple_projections():

    projections = [
        ccrs.PlateCarree(),
        ccrs.Robinson(),
        ccrs.RotatedPole(pole_latitude=45, pole_longitude=180),
        ccrs.OSGB(approx=True),
        ccrs.TransverseMercator(approx=True),
        ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)),
                      min_latitude=-85.,
                      max_latitude=85.),
        ccrs.LambertCylindrical(),
        ccrs.Miller(),
        ccrs.Gnomonic(),
        ccrs.Stereographic(),
        ccrs.NorthPolarStereo(),
        ccrs.SouthPolarStereo(),
        ccrs.Orthographic(),
        ccrs.Mollweide(),
        ccrs.InterruptedGoodeHomolosine(emphasis='land'),
        ccrs.EckertI(),
        ccrs.EckertII(),
        ccrs.EckertIII(),
        ccrs.EckertIV(),
        ccrs.EckertV(),
        ccrs.EckertVI(),
    ]

    rows = np.ceil(len(projections) / 5).astype(int)

    fig = plt.figure(figsize=(10, 2 * rows))
    for i, prj in enumerate(projections, 1):
        ax = fig.add_subplot(rows, 5, i, projection=prj)

        ax.set_global()

        ax.coastlines(resolution="110m")

        plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree())

        plt.plot([-0.08, 132], [51.53, 43.17],
                 color='red',
                 transform=ccrs.PlateCarree())

        plt.plot([-0.08, 132], [51.53, 43.17],
                 color='blue',
                 transform=ccrs.Geodetic())
예제 #28
0
def test_multiple_projections():

    projections = [
        ccrs.PlateCarree(),
        ccrs.Robinson(),
        ccrs.RotatedPole(pole_latitude=45, pole_longitude=180),
        ccrs.OSGB(),
        ccrs.TransverseMercator(),
        ccrs.Mercator(globe=ccrs.Globe(semimajor_axis=math.degrees(1)),
                      min_latitude=-85.,
                      max_latitude=85.),
        ccrs.LambertCylindrical(),
        ccrs.Miller(),
        ccrs.Gnomonic(),
        ccrs.Stereographic(),
        ccrs.NorthPolarStereo(),
        ccrs.SouthPolarStereo(),
        ccrs.Orthographic(),
        ccrs.Mollweide(),
        ccrs.InterruptedGoodeHomolosine(),
    ]

    if ccrs.PROJ4_VERSION < (5, 0, 0):
        # Produce the same sized image for old proj, to avoid having to replace
        # the image. If this figure is regenerated for both old and new proj,
        # then drop this condition.
        rows = 5
    else:
        rows = np.ceil(len(projections) / 5)

    fig = plt.figure(figsize=(10, 2 * rows))
    for i, prj in enumerate(projections, 1):
        ax = fig.add_subplot(rows, 5, i, projection=prj)

        ax.set_global()

        ax.coastlines()

        plt.plot(-0.08, 51.53, 'o', transform=ccrs.PlateCarree())

        plt.plot([-0.08, 132], [51.53, 43.17],
                 color='red',
                 transform=ccrs.PlateCarree())

        plt.plot([-0.08, 132], [51.53, 43.17],
                 color='blue',
                 transform=ccrs.Geodetic())
예제 #29
0
def plot_single_i_metric(da: xr.DataArray) -> None:
    """Plot single i metric plot with viridis colormap.

    Args:
        da (xr.DataArray): i metric dataarray.
    """
    carree = ccrs.PlateCarree()
    map_proj = ccrs.SouthPolarStereo()
    pairs = da.coords[cst.P_COORD].values.shape[0]

    gs = GridSpec(
        nrows=2,
        ncols=pairs,
        width_ratios=[1 / pairs for x in range(pairs)],
        height_ratios=[1, 0.05],
        wspace=0.15,
    )

    fig = plt.gcf()

    ax1 = fig.add_subplot(gs[0, :], projection=map_proj)
    cbar_axes = [fig.add_subplot(gs[1, i]) for i in range(pairs)]

    mp.southern_ocean_axes_setup(ax1, fig)
    cmap_list = col.return_list_of_colormaps(pairs, fade_to_white=False)

    for i in range(pairs):
        im = da.isel(pair=i).plot(
            cmap=cmap_list[i],
            vmin=0,
            vmax=1,
            ax=ax1,
            add_colorbar=False,
            transform=carree,
            subplot_kws={"projection": map_proj},
        )
        cbar = plt.colorbar(im,
                            cax=cbar_axes[i],
                            orientation="horizontal",
                            ticks=[0, 1])
        cbar.set_label(da.coords[cst.P_COORD].values[i])
    plt.suptitle("")
    plt.title("")
    ax1.set_title("")
예제 #30
0
def plot(lat, lon, Z, date, time, intfactor, maxtec, coordsystem, plottype, extent, supermag, rotate):

    if rotate:
        central_lon = 360.0 - 15*time.hour - .25*time.minute
    else:
        central_lon = 0.0
    tecmap = plt.figure(figsize=(11,8))
    
    magstations = genfromtxt('./gps_tec/20200515-23-45-supermag-stations.csv', delimiter=',')
    if plottype ==  'Northern Hemisphere':
        map_proj = ccrs.NorthPolarStereo(central_longitude=central_lon)
    elif plottype == 'Southern Hemisphere':
        map_proj = ccrs.SouthPolarStereo(central_longitude=(central_lon - 180.0))
    elif plottype == 'Global':
        map_proj = ccrs.PlateCarree()
    if coordsystem=='AACGMv2' or coordsystem=='IGRF':
        ax = tecmap.add_subplot(projection='aacgmv2',map_projection = map_proj)
        ax.overaly_coast_lakes(coords="aacgmv2", plot_date=date)
                
        
        if map_proj == ccrs.PlateCarree():
            mesh = ax.pcolor(lon, lat, Z, cmap='jet', vmax=maxtec, transform=ccrs.PlateCarree()) 
        else:
            mesh = ax.scatter(lon, lat, c=Z, cmap='jet', vmax=maxtec, transform=ccrs.PlateCarree(), edgecolor='none')
    
    else:
        #usepcolormesh in 
        ax = plt.axes(projection=map_proj)
        ax.add_feature(cfeature.COASTLINE)
        #ax.add_feature(cfeature.LAKES)
        mesh = ax.pcolormesh(lon, lat, Z, cmap='jet', vmax=maxtec, transform=ccrs.PlateCarree())
        if(supermag):
            magx = magstations[1:, 1]
            magx = magx
            magy = magstations[1:, 2]
            ax.scatter(magx, magy, c='black', transform=ccrs.PlateCarree())            
    
    ax.set_extent(extent, ccrs.PlateCarree())
    clrbar = plt.colorbar(mesh, shrink=0.5)
    clrbar.set_label('Total Electron Content (TECU)')
    ax.gridlines(linewidth=0.5)
    plt.title('Total Electron Content for ' + str(date.month) + '/' + str(date.day) + '/' + str(date.year) + ' at ' + str(time.hour) + ':' + ('%02d' % time.minute) + ' UT')
    st.pyplot(tecmap)