コード例 #1
0
    def test_central_longitude(self, lon):
        eqdc = ccrs.EquidistantConic()
        eqdc_offset = ccrs.EquidistantConic(central_longitude=lon)
        other_args = {'ellps=WGS84', 'lon_0={}'.format(lon), 'lat_0=0.0',
                      'x_0=0.0', 'y_0=0.0', 'lat_1=20.0', 'lat_2=50.0'}
        check_proj4_params(eqdc_offset, other_args)

        assert_array_almost_equal(eqdc_offset.boundary, eqdc.boundary,
                                  decimal=0)
コード例 #2
0
    def test_standard_parallels(self):
        eqdc = ccrs.EquidistantConic(standard_parallels=(13, 37))
        other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0',
                      'y_0=0.0', 'lat_1=13', 'lat_2=37'}
        check_proj4_params(eqdc, other_args)

        eqdc = ccrs.EquidistantConic(standard_parallels=(13, ))
        other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0',
                      'y_0=0.0', 'lat_1=13'}
        check_proj4_params(eqdc, other_args)

        eqdc = ccrs.EquidistantConic(standard_parallels=13)
        other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0',
                      'y_0=0.0', 'lat_1=13'}
        check_proj4_params(eqdc, other_args)
コード例 #3
0
    def test_ellipsoid_transform(self):
        # USGS Professional Paper 1395, pp 299--300
        globe = ccrs.Globe(semimajor_axis=6378206.4,
                           flattening=1 - np.sqrt(1 - 0.00676866),
                           ellipse=None)
        lat_1 = 29.5
        lat_2 = 45.5
        eqdc = ccrs.EquidistantConic(central_latitude=23.0,
                                     central_longitude=-96.0,
                                     standard_parallels=(lat_1, lat_2),
                                     globe=globe)
        geodetic = eqdc.as_geodetic()

        other_args = {
            'a=6378206.4', 'f=0.003390076308689371', 'lon_0=-96.0',
            'lat_0=23.0', 'x_0=0.0', 'y_0=0.0', 'lat_1=29.5', 'lat_2=45.5'
        }
        check_proj_params('eqdc', eqdc, other_args)

        assert_almost_equal(np.array(eqdc.x_limits),
                            (-22421870.719894886, 22421870.719894886),
                            decimal=7)
        assert_almost_equal(np.array(eqdc.y_limits),
                            (-12546277.778958388, 17260638.403203618),
                            decimal=7)

        result = eqdc.transform_point(-75.0, 35.0, geodetic)

        assert_almost_equal(result, (1885051.9, 1540507.6), decimal=1)
コード例 #4
0
    def test_sphere_transform(self):
        # USGS Professional Paper 1395, pg 298
        globe = ccrs.Globe(semimajor_axis=1.0,
                           semiminor_axis=1.0,
                           ellipse=None)
        lat_1 = 29.5
        lat_2 = 45.5
        eqdc = ccrs.EquidistantConic(central_longitude=-96.0,
                                     central_latitude=23.0,
                                     standard_parallels=(lat_1, lat_2),
                                     globe=globe)
        geodetic = eqdc.as_geodetic()

        other_args = {
            'a=1.0', 'b=1.0', 'lon_0=-96.0', 'lat_0=23.0', 'x_0=0.0',
            'y_0=0.0', 'lat_1=29.5', 'lat_2=45.5'
        }
        check_proj_params('eqdc', eqdc, other_args)

        assert_almost_equal(np.array(eqdc.x_limits),
                            (-3.520038619089038, 3.520038619089038),
                            decimal=7)
        assert_almost_equal(np.array(eqdc.y_limits),
                            (-1.9722220547535922, 2.7066811021065535),
                            decimal=7)

        result = eqdc.transform_point(-75.0, 35.0, geodetic)

        assert_almost_equal(result, (0.2952057, 0.2424021), decimal=7)
コード例 #5
0
    def test_eastings(self):
        eqdc_offset = ccrs.EquidistantConic(false_easting=1234,
                                            false_northing=-4321)

        other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=1234',
                      'y_0=-4321', 'lat_1=20.0', 'lat_2=50.0'}
        check_proj4_params(eqdc_offset, other_args)
コード例 #6
0
    def test_default(self):
        eqdc = ccrs.EquidistantConic()
        other_args = {'ellps=WGS84', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0',
                      'y_0=0.0', 'lat_1=20.0', 'lat_2=50.0'}
        check_proj4_params(eqdc, other_args)

        assert_almost_equal(np.array(eqdc.x_limits),
                            (-22784919.35600352, 22784919.35600352),
                            decimal=7)
        assert_almost_equal(np.array(eqdc.y_limits),
                            (-10001965.729313632, 17558791.85156368),
                            decimal=7)
コード例 #7
0
    def test_eccentric_globe(self):
        globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500,
                           ellipse=None)
        eqdc = ccrs.EquidistantConic(globe=globe)
        other_args = {'a=1000', 'b=500', 'lon_0=0.0', 'lat_0=0.0', 'x_0=0.0',
                      'y_0=0.0', 'lat_1=20.0', 'lat_2=50.0'}
        check_proj4_params(eqdc, other_args)

        assert_almost_equal(np.array(eqdc.x_limits),
                            (-3016.869847713461, 3016.869847713461),
                            decimal=7)
        assert_almost_equal(np.array(eqdc.y_limits),
                            (-1216.6029342241113, 2511.0574375797723),
                            decimal=7)
コード例 #8
0
def data_analysis(modN, modE, radVel, radLon, radLat, degs):

    ax = plt.axes(projection=ccrs.EquidistantConic(standard_parallels=(90,
                                                                       90)))
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.OCEAN)

    ax.set_extent([-140, 6, 68, 88], ccrs.PlateCarree())
    gl = ax.gridlines(
        crs=ccrs.PlateCarree(),
        draw_labels=True,
        linewidth=2,
        color='gray',
        alpha=0.5,
        linestyle='-',
    )

    modVels = [
        modN * np.cos(np.deg2rad(degs)), modE * np.sin(np.deg2rad(degs))
    ]
    radar_los = np.array([np.cos(degs), np.sin(degs)])
    model_los_projections = np.dot(np.array(modVels), radar_los)

    print(model_los_projections)
    difs = radVel - model_los_projections

    plt.scatter(radLon,
                radLat,
                c=difs,
                cmap="PuRd",
                transform=ccrs.PlateCarree())

    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER

    gl.xlabel_style = {'size': 15, 'color': 'gray'}
    gl.ylabel_style = {'size': 15, 'color': 'gray'}
    gl.xlabels_top = False
    gl.ylabels_left = False

    clb = plt.colorbar()
    clb.ax.set_title("Velocity")
    clb.set_label("m/s", rotation=270)

    plt.suptitle("Velocity Differences")

    plt.show()
コード例 #9
0
ファイル: mapping.py プロジェクト: alexkjames/Pyleoclim_util
def set_proj(projection='Robinson', proj_default=True):
    """ Set the projection for Cartopy.
    
    Parameters
    ----------
    
    projection : string
        the map projection. Available projections:
        'Robinson' (default), 'PlateCarree', 'AlbertsEqualArea',
        'AzimuthalEquidistant','EquidistantConic','LambertConformal',
        'LambertCylindrical','Mercator','Miller','Mollweide','Orthographic',
        'Sinusoidal','Stereographic','TransverseMercator','UTM',
        'InterruptedGoodeHomolosine','RotatedPole','OSGB','EuroPP',
        'Geostationary','NearsidePerspective','EckertI','EckertII',
        'EckertIII','EckertIV','EckertV','EckertVI','EqualEarth','Gnomonic',
        'LambertAzimuthalEqualArea','NorthPolarStereo','OSNI','SouthPolarStereo'
    proj_default : bool
        If True, uses the standard projection attributes from Cartopy.
        Enter new attributes in a dictionary to change them. Lists of attributes
        can be found in the Cartopy documentation: 
            https://scitools.org.uk/cartopy/docs/latest/crs/projections.html#eckertiv
    
    Returns
    -------
        proj : the Cartopy projection object
        
    See Also
    --------
    pyleoclim.utils.mapping.map_all : mapping function making use of the projection
    
    """
    if proj_default is not True and type(proj_default) is not dict:
        raise TypeError(
            'The default for the projections should either be provided' +
            ' as a dictionary or set to True')

    # Set the projection
    if projection == 'Robinson':
        if proj_default is True:
            proj = ccrs.Robinson()
        else:
            proj = ccrs.Robinson(**proj_default)
    elif projection == 'PlateCarree':
        if proj_default is True:
            proj = ccrs.PlateCarree()
        else:
            proj = ccrs.PlateCarree(**proj_default)
    elif projection == 'AlbersEqualArea':
        if proj_default is True:
            proj = ccrs.AlbersEqualArea()
        else:
            proj = ccrs.AlbersEqualArea(**proj_default)
    elif projection == 'AzimuthalEquidistant':
        if proj_default is True:
            proj = ccrs.AzimuthalEquidistant()
        else:
            proj = ccrs.AzimuthalEquidistant(**proj_default)
    elif projection == 'EquidistantConic':
        if proj_default is True:
            proj = ccrs.EquidistantConic()
        else:
            proj = ccrs.EquidistantConic(**proj_default)
    elif projection == 'LambertConformal':
        if proj_default is True:
            proj = ccrs.LambertConformal()
        else:
            proj = ccrs.LambertConformal(**proj_default)
    elif projection == 'LambertCylindrical':
        if proj_default is True:
            proj = ccrs.LambertCylindrical()
        else:
            proj = ccrs.LambertCylindrical(**proj_default)
    elif projection == 'Mercator':
        if proj_default is True:
            proj = ccrs.Mercator()
        else:
            proj = ccrs.Mercator(**proj_default)
    elif projection == 'Miller':
        if proj_default is True:
            proj = ccrs.Miller()
        else:
            proj = ccrs.Miller(**proj_default)
    elif projection == 'Mollweide':
        if proj_default is True:
            proj = ccrs.Mollweide()
        else:
            proj = ccrs.Mollweide(**proj_default)
    elif projection == 'Orthographic':
        if proj_default is True:
            proj = ccrs.Orthographic()
        else:
            proj = ccrs.Orthographic(**proj_default)
    elif projection == 'Sinusoidal':
        if proj_default is True:
            proj = ccrs.Sinusoidal()
        else:
            proj = ccrs.Sinusoidal(**proj_default)
    elif projection == 'Stereographic':
        if proj_default is True:
            proj = ccrs.Stereographic()
        else:
            proj = ccrs.Stereographic(**proj_default)
    elif projection == 'TransverseMercator':
        if proj_default is True:
            proj = ccrs.TransverseMercator()
        else:
            proj = ccrs.TransverseMercator(**proj_default)
    elif projection == 'TransverseMercator':
        if proj_default is True:
            proj = ccrs.TransverseMercator()
        else:
            proj = ccrs.TransverseMercator(**proj_default)
    elif projection == 'UTM':
        if proj_default is True:
            proj = ccrs.UTM()
        else:
            proj = ccrs.UTM(**proj_default)
    elif projection == 'UTM':
        if proj_default is True:
            proj = ccrs.UTM()
        else:
            proj = ccrs.UTM(**proj_default)
    elif projection == 'InterruptedGoodeHomolosine':
        if proj_default is True:
            proj = ccrs.InterruptedGoodeHomolosine()
        else:
            proj = ccrs.InterruptedGoodeHomolosine(**proj_default)
    elif projection == 'RotatedPole':
        if proj_default is True:
            proj = ccrs.RotatedPole()
        else:
            proj = ccrs.RotatedPole(**proj_default)
    elif projection == 'OSGB':
        if proj_default is True:
            proj = ccrs.OSGB()
        else:
            proj = ccrs.OSGB(**proj_default)
    elif projection == 'EuroPP':
        if proj_default is True:
            proj = ccrs.EuroPP()
        else:
            proj = ccrs.EuroPP(**proj_default)
    elif projection == 'Geostationary':
        if proj_default is True:
            proj = ccrs.Geostationary()
        else:
            proj = ccrs.Geostationary(**proj_default)
    elif projection == 'NearsidePerspective':
        if proj_default is True:
            proj = ccrs.NearsidePerspective()
        else:
            proj = ccrs.NearsidePerspective(**proj_default)
    elif projection == 'EckertI':
        if proj_default is True:
            proj = ccrs.EckertI()
        else:
            proj = ccrs.EckertI(**proj_default)
    elif projection == 'EckertII':
        if proj_default is True:
            proj = ccrs.EckertII()
        else:
            proj = ccrs.EckertII(**proj_default)
    elif projection == 'EckertIII':
        if proj_default is True:
            proj = ccrs.EckertIII()
        else:
            proj = ccrs.EckertIII(**proj_default)
    elif projection == 'EckertIV':
        if proj_default is True:
            proj = ccrs.EckertIV()
        else:
            proj = ccrs.EckertIV(**proj_default)
    elif projection == 'EckertV':
        if proj_default is True:
            proj = ccrs.EckertV()
        else:
            proj = ccrs.EckertV(**proj_default)
    elif projection == 'EckertVI':
        if proj_default is True:
            proj = ccrs.EckertVI()
        else:
            proj = ccrs.EckertVI(**proj_default)
    elif projection == 'EqualEarth':
        if proj_default is True:
            proj = ccrs.EqualEarth()
        else:
            proj = ccrs.EqualEarth(**proj_default)
    elif projection == 'Gnomonic':
        if proj_default is True:
            proj = ccrs.Gnomonic()
        else:
            proj = ccrs.Gnomonic(**proj_default)
    elif projection == 'LambertAzimuthalEqualArea':
        if proj_default is True:
            proj = ccrs.LambertAzimuthalEqualArea()
        else:
            proj = ccrs.LambertAzimuthalEqualArea(**proj_default)
    elif projection == 'NorthPolarStereo':
        if proj_default is True:
            proj = ccrs.NorthPolarStereo()
        else:
            proj = ccrs.NorthPolarStereo(**proj_default)
    elif projection == 'OSNI':
        if proj_default is True:
            proj = ccrs.OSNI()
        else:
            proj = ccrs.OSNI(**proj_default)
    elif projection == 'OSNI':
        if proj_default is True:
            proj = ccrs.SouthPolarStereo()
        else:
            proj = ccrs.SouthPolarStereo(**proj_default)
    else:
        raise ValueError('Invalid projection type')

    return proj
コード例 #10
0
ファイル: test.py プロジェクト: opinner/MasterThesis
import cartopy.feature as cfeature


def mm_to_inches(a, b):
    (a, b) = (a * 0.0393701, b * 0.0393701)
    return (a, b)


fig = plt.figure(figsize=mm_to_inches(190, 115))

gs = fig.add_gridspec(3, 3)

central_lon, central_lat = 19.5, 58.5
projection = ccrs.EquidistantConic(central_lon,
                                   central_lat,
                                   false_easting=0.0,
                                   false_northing=0.0,
                                   standard_parallels=(20.0, 50.0),
                                   globe=None)

ax1 = fig.add_subplot(gs[:, 0:2], projection=projection)
ax1.set_extent([12, 27.5, 53, 65])  #, crs = projection)
ax1.coastlines(resolution='auto', color='k')
gl = ax1.gridlines(color='lightgrey', linestyle='-', draw_labels=True)
#gl = ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
gl.top_labels = False
gl.right_labels = False

ax2 = fig.add_subplot(gs[:, 2])
ax2.plot([1, 2], [3, 4])
ax2b = ax2.twinx()
ax2b.plot([1, 2], [40, 30])
コード例 #11
0
ファイル: feems_mix.py プロジェクト: VivaswatS/feems
    def __init__(self,
                 genotypes,
                 sample_pos,
                 node_pos,
                 edges,
                 scale_snps=True,
                 n_lre=0,
                 n_folds=None,
                 search='Hull'):
        """Represents the meta-list of spatial graphs which the data is defined on and
        performs relevant computations and operations to help choose the long range edges. 

        Args:
            genotypes (:obj:`numpy.ndarray`): genotypes for samples
            sample_pos (:obj:`numpy.ndarray`): spatial positions for samples
            node_pos (:obj:`numpy.ndarray`):  spatial positions of nodes
            edges (:obj:`numpy.ndarray`): edge array
            scale_snps (:obj:`Bool`): boolean to scale SNPs by SNP specific
                Binomial variance estimates
            n_lre (:obj:`int`): number of long range edges to add
            n_folds (:obj:`int`): number of folds to run CV over - default is leave-one-out
            search (:obj:`str`): type of search to find best fit long range edge -  default is convex hull
        """
        # check inputs
        assert len(genotypes.shape) == 2
        assert len(sample_pos.shape) == 2
        assert np.all(~np.isnan(genotypes)), "no missing genotypes are allowed"
        assert np.all(~np.isinf(genotypes)), "non inf genotypes are allowed"
        assert (genotypes.shape[0] == sample_pos.shape[0]
                ), "genotypes and sample positions must be the same size"
        assert type(
            n_lre) == int or n_lre is None, "n_lre should be an integer"
        assert search in [
            'Global', 'Hull', 'Top-N'
        ], "search should be a string, one of Global/Hull/Top-N"

        # creating a projection vector
        projection = ccrs.EquidistantConic(
            central_longitude=np.median(sample_pos[:, 0]),
            central_latitude=np.median(sample_pos[:, 1]))

        # creating the default graph
        self.graph = []
        self.graph.append(SpatialGraph(genotypes, sample_pos, node_pos, edges))

        # plotting the samples map with overlaid grid
        fig = plt.figure(dpi=100)
        ax = fig.add_subplot(1, 1, 1, projection=projection)
        v = Viz(ax,
                self.graph[0],
                projection=projection,
                edge_width=.5,
                edge_alpha=1,
                edge_zorder=100,
                sample_pt_size=10,
                obs_node_size=7.5,
                sample_pt_color="black",
                cbar_font_size=10)
        v.draw_map()
        v.draw_samples()
        v.draw_edges(use_weights=False)
        v.draw_obs_nodes(use_ids=False)

        # running the CV step to compute 'best' lambda fit
        lamb_grid = np.geomspace(1e-6, 1e2, 20)[::-1]
        cv_err = run_cv(self.graph[0], lamb_grid, n_folds=n_folds, factr=1e10)
        lamb_cv = float(lamb_grid[np.argmin(np.mean(cv_err, axis=0))])

        print("\n")
        # plotting the genetic vs fitted distance to assess goodness of fit & returning pair of nodes with maximum abs residual
        max_res_nodes = comp_genetic_vs_fitted_distance(self.graph[0],
                                                        lamb=lamb_cv,
                                                        plotFig=True,
                                                        n_lre=1)

        obj = Objective(self.graph[0])
        obj._solve_lap_sys()
        obj._comp_mat_block_inv()
        obj._comp_inv_cov()
        self.nll = list()
        self.nll.append(obj.neg_log_lik())

        fig = plt.figure(dpi=100)
        ax = fig.add_subplot(1, 1, 1, projection=projection)
        v = Viz(ax,
                self.graph[0],
                projection=projection,
                edge_width=.5,
                edge_alpha=1,
                edge_zorder=100,
                sample_pt_size=20,
                obs_node_size=7.5,
                sample_pt_color="black",
                cbar_font_size=10)
        v.draw_map()
        v.draw_edges(use_weights=True)
        v.draw_obs_nodes(use_ids=False)
        v.draw_edge_colorbar()

        # TODO: plot the lower triangular residual matrix here

        if n_lre is None:
            # TODO: fill in code here for running the case when we stop based on a condition...
            1 + 1  # placeholder
        elif n_lre > 0:
            # creating a copy of the edges of default graph to set us off
            temp_edges = deepcopy(edges.tolist())
            for n in np.arange(1, n_lre + 1):
                # need to select based on a flag here...
                temp_edges.append(list(x + 1 for x in max_res_nodes[0]))

                self.graph.append(
                    SpatialGraph(genotypes, sample_pos, node_pos,
                                 np.array(temp_edges)))

                lamb_grid = np.geomspace(1e-6, 1e2, 20)[::-1]
                cv_err = run_cv(self.graph[n],
                                lamb_grid,
                                n_folds=n_folds,
                                factr=1e10)
                lamb_cv_lr = float(lamb_grid[np.argmin(np.mean(cv_err,
                                                               axis=0))])

                # this is where the search functions will go - graph already created, has one max_res_node
                best_fit_nodes = self._search_hull(n, max_res_nodes,
                                                   lamb_cv_lr)

                # create a vector of nll fits for best long range edge
                self.nll.append(best_fit_nodes.loc[1, 'nll'])

                # replace the max_res_node edge with the best fit
                if (max_res_nodes[0] != best_fit_nodes.loc[1, 'nodes']):
                    self.graph[n].remove_edge(*best_fit_nodes.loc[0, 'nodes'])
                    self.graph[n].add_edge(*best_fit_nodes.loc[1, 'nodes'])
                    temp_edges[temp_edges.index(
                        list(x + 1 for x in max_res_nodes[0]))] = list(
                            x + 1 for x in best_fit_nodes.loc[1, 'nodes'])

                # TODO: do nll p-value calc here and output more informative message
                if (self.nll[n] < self.nll[0]):
                    print(
                        "Model with long-range edges fits better than default by %.2f log units with p-value of %.2e"
                        % (2. * (self.nll[0] - self.nll[n]),
                           chi2.sf(2. * (self.nll[0] - self.nll[n]), n)))
                else:
                    print(
                        "Default model fits better than model with long range edges"
                    )

                max_res_nodes = comp_genetic_vs_fitted_distance(self.graph[n],
                                                                lamb=lamb_cv,
                                                                plotFig=False,
                                                                n_lre=1)

            # plot the final graph against the default (do row-wise potentially -- better for bigger graphs)
            self.lre = list(
                set([tuple((x[0] - 1, x[1] - 1))
                     for x in temp_edges]) - set(list(self.graph[0].edges)))
            plot_default_vs_long_range(self.graph[0],
                                       self.graph[n_lre],
                                       max_res_nodes=self.lre,
                                       lamb=np.array((lamb_cv, lamb_cv_lr)))
コード例 #12
0
def plot_data(modData,
              radarData,
              time,
              index,
              hrind,
              axext=[-140, 6, 68, 88],
              filename="Inuvik.png"):

    #convert data into numpy array
    for key, value in radarData.items():
        radarData[key] = np.array(value)

    uniqueTimes = np.unique(radarData["mjd"])
    timeIndex = radarData["mjd"] == uniqueTimes[index]

    #isolate data for a certain time code
    fsLatTimed = radarData["geolat"][timeIndex]
    fsLonTimed = radarData["geolon"][timeIndex]
    fsVelTimed = radarData["vel"][timeIndex]

    fsVelNTimed = radarData["vel_n"][timeIndex]
    fsVelETimed = radarData["vel_e"][timeIndex]
    fsDegTimed = radarData["geoazm"][timeIndex]

    # set up the plot
    ax = plt.axes(projection=ccrs.EquidistantConic(standard_parallels=(90,
                                                                       90)))
    ax.coastlines()
    ax.gridlines()
    ax.set_extent(axext, ccrs.PlateCarree())

    #plot model data
    plt.quiver(
        modData["lon0"]["vals"].flatten(),
        modData["lat0"]["vals"].flatten(),
        modData["uphi"]["vals"][hrind, :, :].flatten(),
        modData["utheta"]["vals"][hrind, :, :].flatten(),
        color="gray",
        transform=ccrs.PlateCarree(),
        regrid_shape=24,
        width=.005,
    )

    #plot radar data
    plt.quiver(
        fsLonTimed,
        fsLatTimed,
        fsVelETimed,
        fsVelNTimed,
        color="magenta",
        transform=ccrs.PlateCarree(),
    )
    #add radar location
    plt.plot(-133.772,
             68.414,
             color="red",
             marker="x",
             transform=ccrs.PlateCarree())

    #add plot legend
    magenta = mpatches.Patch(color='magenta', label='Radar Velocities')
    gray = mpatches.Patch(color='gray', label='Model Velocities')
    plt.legend(handles=[magenta, gray],
               bbox_to_anchor=(1.05, 1),
               loc='upper left',
               borderaxespad=0.)

    #title and save file
    plt.suptitle(
        time.strftime("SAMI/AMPERE ExB drift vels at %H:%M UT on %d %b %Y"))
    plt.savefig(filename, dpi=300)
    plt.show()
    plt.close()

    return fsVelTimed, fsLonTimed, fsLatTimed, fsDegTimed
コード例 #13
0
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

plt.figure(figsize=(4.9603, 3))
ax = plt.axes(projection=ccrs.EquidistantConic())
ax.coastlines(resolution='110m')
ax.gridlines()
コード例 #14
0
def get_map_projection(
        proj_name,
        central_longitude=0.0,
        central_latitude=0.0,
        false_easting=0.0,
        false_northing=0.0,
        globe=None,
        standard_parallels=(20.0, 50.0),
        scale_factor=None,
        min_latitude=-80.0,
        max_latitude=84.0,
        true_scale_latitude=None,
        latitude_true_scale=None,  ### BOTH
        secant_latitudes=None,
        pole_longitude=0.0,
        pole_latitude=90.0,
        central_rotated_longitude=0.0,
        sweep_axis='y',
        satellite_height=35785831,
        cutoff=-30,
        approx=None,
        southern_hemisphere=False,
        zone=15):  #### numeric UTM zone

    proj_name = proj_name.lower()

    if (proj_name == 'albersequalarea'):
        proj = ccrs.AlbersEqualArea(central_longitude=central_longitude,
                                    central_latitude=central_latitude,
                                    false_easting=false_easting,
                                    false_northing=false_northing,
                                    globe=globe,
                                    standard_parallels=standard_parallels)
    elif (proj_name == 'azimuthalequidistant'):
        proj = ccrs.AzimuthalEquidistant(central_longitude=central_longitude,
                                         central_latitude=central_latitude,
                                         false_easting=false_easting,
                                         false_northing=false_northing,
                                         globe=globe)
    elif (proj_name == 'equidistantconic'):
        proj = ccrs.EquidistantConic(central_longitude=central_longitude,
                                     central_latitude=central_latitude,
                                     false_easting=false_easting,
                                     false_northing=false_northing,
                                     globe=globe,
                                     standard_parallels=standard_parallels)
    elif (proj_name == 'lambertconformal'):
        proj = ccrs.LambertConformal(
            central_longitude=-96.0,  ##########
            central_latitude=39.0,  ##########
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            secant_latitudes=None,
            standard_parallels=None,  ## default: (33,45)
            cutoff=cutoff)
    elif (proj_name == 'lambertcylindrical'):
        proj = ccrs.LambertCylindrical(central_longitude=central_longitude)
    elif (proj_name == 'mercator'):
        proj = ccrs.Mercator(central_longitude=central_longitude,
                             min_latitude=min_latitude,
                             max_latitude=max_latitude,
                             latitude_true_scale=latitude_true_scale,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe,
                             scale_factor=None)  #########
    elif (proj_name == 'miller'):
        proj = ccrs.Miller(central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'mollweide'):
        proj = ccrs.Mollweide(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'orthographic'):
        proj = ccrs.Orthographic(central_longitude=central_longitude,
                                 central_latitude=central_latitude,
                                 globe=globe)
    elif (proj_name == 'robinson'):
        proj = ccrs.Robinson(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'sinusoidal'):
        proj = ccrs.Sinusoidal(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'stereographic'):
        proj = ccrs.Stereographic(central_latitude=central_latitude,
                                  central_longitude=central_longitude,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  true_scale_latitude=true_scale_latitude,
                                  scale_factor=scale_factor)
    elif (proj_name == 'transversemercator'):
        proj = ccrs.TransverseMercator(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            false_easting=false_easting,
            false_northing=false_northing,
            globe=globe,
            scale_factor=1.0,  ##########
            approx=approx)
    elif (proj_name == 'utm'):
        proj = ccrs.UTM(zone,
                        southern_hemisphere=southern_hemisphere,
                        globe=globe)
    elif (proj_name == 'interruptedgoodehomolosine'):
        proj = ccrs.InterruptedGoodeHomolosine(
            central_longitude=central_longitude, globe=globe)
    elif (proj_name == 'rotatedpole'):
        proj = ccrs.RotatedPole(
            pole_longitude=pole_longitude,
            pole_latitude=pole_latitude,
            globe=globe,
            central_rotated_longitude=central_rotated_longitude)
    elif (proj_name == 'osgb'):
        proj = ccrs.OSGB(approx=approx)
    elif (proj_name == 'europp'):
        proj = ccrs.EuroPP
    elif (proj_name == 'geostationary'):
        proj = ccrs.Geostationary(central_longitude=central_longitude,
                                  satellite_height=satellite_height,
                                  false_easting=false_easting,
                                  false_northing=false_northing,
                                  globe=globe,
                                  sweep_axis=sweep_axis)
    elif (proj_name == 'nearsideperspective'):
        proj = ccrs.NearsidePerspective(central_longitude=central_longitude,
                                        central_latitude=central_latitude,
                                        satellite_height=satellite_height,
                                        false_easting=false_easting,
                                        false_northing=false_northing,
                                        globe=globe)
    elif (proj_name == 'eckerti'):
        proj = ccrs.EckertI(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertii'):
        proj = ccrs.EckertII(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertiii'):
        proj = ccrs.EckertIII(central_longitude=central_longitude,
                              false_easting=false_easting,
                              false_northing=false_northing,
                              globe=globe)
    elif (proj_name == 'eckertiv'):
        proj = ccrs.EckertIV(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'eckertv'):
        proj = ccrs.EckertV(central_longitude=central_longitude,
                            false_easting=false_easting,
                            false_northing=false_northing,
                            globe=globe)
    elif (proj_name == 'eckertvi'):
        proj = ccrs.EckertVI(central_longitude=central_longitude,
                             false_easting=false_easting,
                             false_northing=false_northing,
                             globe=globe)
    elif (proj_name == 'equalearth'):
        proj = ccrs.EqualEarth(central_longitude=central_longitude,
                               false_easting=false_easting,
                               false_northing=false_northing,
                               globe=globe)
    elif (proj_name == 'gnomonic'):
        proj = ccrs.Gnomonic(central_latitude=central_latitude,
                             central_longitude=central_longitude,
                             globe=globe)
    elif (proj_name == 'lambertazimuthalequalarea'):
        proj = ccrs.LambertAzimuthalEqualArea(
            central_longitude=central_longitude,
            central_latitude=central_latitude,
            globe=globe,
            false_easting=false_easting,
            false_northing=false_northing)
    elif (proj_name == 'northpolarstereo'):
        proj = ccrs.NorthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    elif (proj_name == 'osni'):
        proj = ccrs.OSNI(approx=approx)
    elif (proj_name == 'southpolarstereo'):
        proj = ccrs.SouthPolarStereo(central_longitude=central_longitude,
                                     true_scale_latitude=true_scale_latitude,
                                     globe=globe)
    else:
        # This is same as "Geographic coordinates"
        proj = ccrs.PlateCarree(central_longitude=central_longitude,
                                globe=globe)

    return proj
コード例 #15
0
    def projection(self):
        if self.proj is None:
            return ccrs.PlateCarree()

        proj_dict = ast.literal_eval(self.proj)
        user_proj = proj_dict.pop("proj")
        if user_proj == 'PlateCarree':
            self.xylim_supported = True
            return ccrs.PlateCarree(**proj_dict)
        elif user_proj == 'AlbersEqualArea':
            return ccrs.AlbersEqualArea(**proj_dict)
        elif user_proj == 'AzimuthalEquidistant':
            return ccrs.AzimuthalEquidistant(**proj_dict)
        elif user_proj == 'EquidistantConic':
            return ccrs.EquidistantConic(**proj_dict)
        elif user_proj == 'LambertConformal':
            return ccrs.LambertConformal(**proj_dict)
        elif user_proj == 'LambertCylindrical':
            return ccrs.LambertCylindrical(**proj_dict)
        elif user_proj == 'Mercator':
            return ccrs.Mercator(**proj_dict)
        elif user_proj == 'Miller':
            return ccrs.Miller(**proj_dict)
        elif user_proj == 'Mollweide':
            return ccrs.Mollweide(**proj_dict)
        elif user_proj == 'Orthographic':
            return ccrs.Orthographic(**proj_dict)
        elif user_proj == 'Robinson':
            return ccrs.Robinson(**proj_dict)
        elif user_proj == 'Sinusoidal':
            return ccrs.Sinusoidal(**proj_dict)
        elif user_proj == 'Stereographic':
            return ccrs.Stereographic(**proj_dict)
        elif user_proj == 'TransverseMercator':
            return ccrs.TransverseMercator(**proj_dict)
        elif user_proj == 'UTM':
            return ccrs.UTM(**proj_dict)
        elif user_proj == 'InterruptedGoodeHomolosine':
            return ccrs.InterruptedGoodeHomolosine(**proj_dict)
        elif user_proj == 'RotatedPole':
            return ccrs.RotatedPole(**proj_dict)
        elif user_proj == 'OSGB':
            self.xylim_supported = False
            return ccrs.OSGB(**proj_dict)
        elif user_proj == 'EuroPP':
            self.xylim_supported = False
            return ccrs.EuroPP(**proj_dict)
        elif user_proj == 'Geostationary':
            return ccrs.Geostationary(**proj_dict)
        elif user_proj == 'NearsidePerspective':
            return ccrs.NearsidePerspective(**proj_dict)
        elif user_proj == 'EckertI':
            return ccrs.EckertI(**proj_dict)
        elif user_proj == 'EckertII':
            return ccrs.EckertII(**proj_dict)
        elif user_proj == 'EckertIII':
            return ccrs.EckertIII(**proj_dict)
        elif user_proj == 'EckertIV':
            return ccrs.EckertIV(**proj_dict)
        elif user_proj == 'EckertV':
            return ccrs.EckertV(**proj_dict)
        elif user_proj == 'EckertVI':
            return ccrs.EckertVI(**proj_dict)
        elif user_proj == 'EqualEarth':
            return ccrs.EqualEarth(**proj_dict)
        elif user_proj == 'Gnomonic':
            return ccrs.Gnomonic(**proj_dict)
        elif user_proj == 'LambertAzimuthalEqualArea':
            return ccrs.LambertAzimuthalEqualArea(**proj_dict)
        elif user_proj == 'NorthPolarStereo':
            return ccrs.NorthPolarStereo(**proj_dict)
        elif user_proj == 'OSNI':
            return ccrs.OSNI(**proj_dict)
        elif user_proj == 'SouthPolarStereo':
            return ccrs.SouthPolarStereo(**proj_dict)
コード例 #16
0
ファイル: Figure2.py プロジェクト: rsellevold/papers
    return data

# Load data
varlist = ["TREFHT", "Z500", "CLDTOT", "PSL", "RADIN", "PRECS"]
for key in varlist:
	f = xr.open_dataset("../models/saved/nn_10/{}/output.nc".format(key))
	vars()["maps_{}".format(key)] = f.featmaps

for key in varlist:
    vars()["maps_{}".format(key)] = add_cyclic(vars()["maps_{}".format(key)])


# Plot
fig = plt.figure(figsize=(7.3,5.5))

proj = ccrs.EquidistantConic(central_longitude=-45)
cmap = plt.get_cmap("RdBu_r")
clevs = np.array([-1, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])
norm = colors.BoundaryNorm(clevs, cmap.N)

xmin = -135
xmax = 45
ymin = 40
ymax = 90
ext = [xmin,xmax,ymin,ymax]


# TREFHT maps (3,0)
ax11 = plt.subplot(5,3,1, projection=ccrs.PlateCarree(central_longitude=-45))
ax11.coastlines(resolution="50m", linewidth=0.5)
ax11.set_title(r"(a) T$_{2m}$", loc="left")
コード例 #17
0
    def to_cartopy_proj(self):
        """
        Creates a `cartopy.crs.Projection` instance from PROJ4 parameters.

        Returns
        -------
        cartopy.crs.projection
            Cartopy projection representing the projection of the spatial reference system.

        """
        proj4_params = self.to_proj4_dict()
        proj4_name = proj4_params.get('proj')
        central_longitude = proj4_params.get('lon_0', 0.)
        central_latitude = proj4_params.get('lat_0', 0.)
        false_easting = proj4_params.get('x_0', 0.)
        false_northing = proj4_params.get('y_0', 0.)
        scale_factor = proj4_params.get('k', 1.)
        standard_parallels = (proj4_params.get('lat_1', 20.),
                              proj4_params.get('lat_2', 50.))

        if proj4_name == 'longlat':
            ccrs_proj = ccrs.PlateCarree(central_longitude)
        elif proj4_name == 'aeqd':
            ccrs_proj = ccrs.AzimuthalEquidistant(central_longitude,
                                                  central_latitude,
                                                  false_easting,
                                                  false_northing)
        elif proj4_name == 'merc':
            ccrs_proj = ccrs.Mercator(central_longitude,
                                      false_easting=false_easting,
                                      false_northing=false_northing,
                                      scale_factor=scale_factor)
        elif proj4_name == 'eck1':
            ccrs_proj = ccrs.EckertI(central_longitude, false_easting,
                                     false_northing)
        elif proj4_name == 'eck2':
            ccrs_proj = ccrs.EckertII(central_longitude, false_easting,
                                      false_northing)
        elif proj4_name == 'eck3':
            ccrs_proj = ccrs.EckertIII(central_longitude, false_easting,
                                       false_northing)
        elif proj4_name == 'eck4':
            ccrs_proj = ccrs.EckertIV(central_longitude, false_easting,
                                      false_northing)
        elif proj4_name == 'eck5':
            ccrs_proj = ccrs.EckertV(central_longitude, false_easting,
                                     false_northing)
        elif proj4_name == 'eck6':
            ccrs_proj = ccrs.EckertVI(central_longitude, false_easting,
                                      false_northing)
        elif proj4_name == 'aea':
            ccrs_proj = ccrs.AlbersEqualArea(central_longitude,
                                             central_latitude, false_easting,
                                             false_northing,
                                             standard_parallels)
        elif proj4_name == 'eqdc':
            ccrs_proj = ccrs.EquidistantConic(central_longitude,
                                              central_latitude, false_easting,
                                              false_northing,
                                              standard_parallels)
        elif proj4_name == 'gnom':
            ccrs_proj = ccrs.Gnomonic(central_longitude, central_latitude)
        elif proj4_name == 'laea':
            ccrs_proj = ccrs.LambertAzimuthalEqualArea(central_longitude,
                                                       central_latitude,
                                                       false_easting,
                                                       false_northing)
        elif proj4_name == 'lcc':
            ccrs_proj = ccrs.LambertConformal(
                central_longitude,
                central_latitude,
                false_easting,
                false_northing,
                standard_parallels=standard_parallels)
        elif proj4_name == 'mill':
            ccrs_proj = ccrs.Miller(central_longitude)
        elif proj4_name == 'moll':
            ccrs_proj = ccrs.Mollweide(central_longitude,
                                       false_easting=false_easting,
                                       false_northing=false_northing)
        elif proj4_name == 'stere':
            ccrs_proj = ccrs.Stereographic(central_latitude,
                                           central_longitude,
                                           false_easting,
                                           false_northing,
                                           scale_factor=scale_factor)
        elif proj4_name == 'ortho':
            ccrs_proj = ccrs.Orthographic(central_longitude, central_latitude)
        elif proj4_name == 'robin':
            ccrs_proj = ccrs.Robinson(central_longitude,
                                      false_easting=false_easting,
                                      false_northing=false_northing)
        elif proj4_name == 'sinus':
            ccrs_proj = ccrs.Sinusoidal(central_longitude, false_easting,
                                        false_northing)
        elif proj4_name == 'tmerc':
            ccrs_proj = ccrs.TransverseMercator(central_longitude,
                                                central_latitude,
                                                false_easting, false_northing,
                                                scale_factor)
        else:
            err_msg = "Projection '{}' is not supported.".format(proj4_name)
            raise ValueError(err_msg)

        return ccrs_proj
コード例 #18
0
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

eq_conic = ccrs.EquidistantConic()
fig = plt.figure(figsize=(10, 5))
ax = plt.axes(projection=eq_conic)
ax.set_global()
ax.gridlines()
ax.stock_img()
ax.coastlines()
plt.show()
コード例 #19
0
def plotMap(op_filepath,
            latMinPlot,
            lonMinPlot,
            latMaxPlot,
            lonMaxPlot,
            samples=None,
            stations=None,
            title=None):
    '''
    Plots a map that can be used to show where samples were taken and/or stations

    Parameters
    ----------
    op_filepath : string
        The filepath where the map will be stored.
    latMinPlot : int
        Minimum latitude to plot, decimal coordinates
    lonMinPlot : int
        Minimum longitude to plot, decimal coordinates
    latMaxPlot : int
        Maximum latitude to plot, decimal coordinates
    lonMaxPlot : int
        Maximum longitude to plot, decimal coordinates
    samples : pandas.dataframe, optional
        Samples to plot on map. The default is None.
    stations : pandas.dataframe, optional
        Stations to plot on map. The default is None.
    title : string, optional
        Option to include a title above the map. The default is None.

    Returns
    -------
    None.

    '''
    plt.figure(figsize=(7, 7))
    ax = plt.axes(projection=ccrs.EquidistantConic())
    ax.gridlines(draw_labels=True, linewidth=1, color='k', linestyle='--')
    ax.add_feature(
        feat.NaturalEarthFeature('physical',
                                 'land',
                                 '10m',
                                 facecolor=feat.COLORS['land'],
                                 edgecolor='black',
                                 linewidth=1.2))
    xlim = [lonMinPlot, lonMaxPlot]
    ylim = [latMinPlot, latMaxPlot]

    rect = mpath.Path([
        [xlim[0], ylim[0]],
        [xlim[1], ylim[0]],
        [xlim[1], ylim[1]],
        [xlim[0], ylim[1]],
        [xlim[0], ylim[0]],
    ]).interpolated(20)

    proj_to_data = ccrs.PlateCarree()._as_mpl_transform(ax) - ax.transData
    rect_in_target = proj_to_data.transform_path(rect)

    ax.set_boundary(rect_in_target)

    ax.set_extent([xlim[0], xlim[1], ylim[0] - 2, ylim[1]])
    ax.stock_img()

    if samples is not None:
        cruises = list(set(samples['cruisenumber'].astype(str)))
        colors = cm.rainbow(np.linspace(0, 1, len(cruises)))
        for cruise, color in zip(cruises, colors):
            cruiseSamples = samples.loc[samples['cruisenumber'].astype(str) ==
                                        cruise]
            ax.scatter(cruiseSamples['decimallongitude'],
                       cruiseSamples['decimallatitude'],
                       color=color,
                       edgecolor='k',
                       marker='.',
                       s=200,
                       transform=ccrs.PlateCarree(),
                       zorder=5,
                       label=cruise)
    if stations is not None:
        ax.scatter(stations['decimalLongitude'],
                   stations['decimalLatitude'],
                   color='grey',
                   edgecolor='k',
                   marker='s',
                   s=200,
                   transform=ccrs.PlateCarree(),
                   zorder=3,
                   label='Stations')
    if title is not None:
        ax.set_title(title, fontsize=18)

    plt.legend(bbox_to_anchor=(1.1, 1.1))
    plt.savefig(op_filepath, bbox_inches='tight')
    plt.close()
コード例 #20
0
ファイル: plot_map_nc.py プロジェクト: alexchartier/superdarn
data = nc_utils.ncread_vars(fn)
times = np.array([dt.datetime.fromtimestamp(t) for t in data['times']])

data['phi'] = np.cos(np.deg2rad(data['gAz'])) * data['vel']
data['theta'] = np.sin(np.deg2rad(data['gAz'])) * data['vel']

#for t in np.unique(times):
tind = times == times[0]

data_t = {}
for k, v in data.items():
    data_t[k] = v[tind]


# set up the plot 
ax = plt.axes(projection=ccrs.EquidistantConic(standard_parallels = (90,90)))
ax.coastlines()
ax.gridlines()
ax.set_extent(axext, ccrs.PlateCarree())


# plot vectors
plt.quiver(
    data_t['gLon'], data_t['gLat'], data_t['phi'], data_t['theta'],
    color = "gray", transform=ccrs.PlateCarree(), width=.002,
)   
plt.show()
    


コード例 #21
0
def plot_data(modData, radarData, time, index, hrind, axext=[-140, 6, 68, 88]):

    for key, value in radarData.items():
        radarData[key] = np.array(value)

    uniqueTimes = np.unique(radarData["mjd"])
    timeIndex = radarData["mjd"] == uniqueTimes[index]

    timedData = {}
    for key, value, in radarData.items():
        timedData[key] = radarData["value"][timeIndex]

    # set up the plot
    ax = plt.axes(projection=ccrs.EquidistantConic(standard_parallels=(90,
                                                                       90)))
    ax.coastlines()
    ax.gridlines()
    ax.set_extent(axext, ccrs.PlateCarree())

    plt.quiver(
        modData["lon0"]["vals"].flatten(),
        modData["lat0"]["vals"].flatten(),
        modData["uphi"]["vals"][hrind, :, :].flatten(),
        modData["utheta"]["vals"][hrind, :, :].flatten(),
        color="gray",
        transform=ccrs.PlateCarree(),
        regrid_shape=24,
        width=.005,
    )

    # make the plot
    plt.quiver(
        timedData["geolon"],
        timedData["geolat"],
        timedData["vel_e"],
        timedData["vel_n"],
        color="magenta",
        transform=ccrs.PlateCarree(),
    )
    plt.plot(-133.772,
             68.414,
             color="red",
             marker="x",
             transform=ccrs.PlateCarree())

    magenta = mpatches.Patch(color='magenta', label='Radar Velocities')
    gray = mpatches.Patch(color='gray', label='Model Velocities')

    plt.legend(handles=[magenta, gray],
               bbox_to_anchor=(1.05, 1),
               loc='upper left',
               borderaxespad=0.)

    plt.suptitle(
        time.strftime("SAMI/AMPERE ExB drift vels at %H:%M UT on %d %b %Y"))
    plt.savefig("Inuvik_NE_4.png", dpi=300)
    plt.show()
    plt.close()

    return timedData["vel"], timedData["geolon"], timedData[
        "geolat"], timedData["geoazm"]
コード例 #22
0
ファイル: cartoee.py プロジェクト: deeplook/geemap
def add_scale_bar(
    ax,
    metric_distance=4,
    unit="km",
    at_x=(0.05, 0.5),
    at_y=(0.08, 0.11),
    max_stripes=5,
    ytick_label_margins=0.25,
    fontsize=8,
    font_weight="bold",
    rotation=0,
    zorder=999,
    paddings={
        "xmin": 0.05,
        "xmax": 0.05,
        "ymin": 1.5,
        "ymax": 0.5
    },
    bbox_kwargs={
        "facecolor": "white",
        "edgecolor": "black",
        "alpha": 0.5
    },
):
    """
    Add a scale bar to the map.

    Args:
        ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object.
        metric_distance (int | float, optional): length in meters of each region of the scale bar. Default to 4.
        unit (str, optinal): scale bar distance unit. Default to "km"
        at_x (float, optional): target axes X coordinates (0..1) of box (= left, right). Default to (0.05, 0.2).
        at_y (float, optional): axes Y coordinates (0..1) of box (= lower, upper). Deafult to (0.08, 0.11).
        max_stripes (int, optional): typical/maximum number of black+white regions. Default to 5.
        ytick_label_margins (float, optional): Location of distance labels on the Y axis. Default to 0.25.
        fontsize (int, optional): scale bar text size. Default to 8.
        font_weight (str, optional):font weight. Default to 'bold'.
        rotation (int, optional): rotation of the length labels for each region of the scale bar. Default to 0.
        zorder (float, optional): z order of the text bounding box.
        paddings (dict, optional): boundaries of the box that contains the scale bar.
        bbox_kwargs (dict, optional): style of the box containing the scale bar.

    """

    import warnings

    warnings.filterwarnings("ignore")

    # --------------------------------------------------------------------------
    # Auxiliary functions

    def _crs_coord_project(crs_target, xcoords, ycoords, crs_source):
        """ metric coordinates (x, y) from cartopy.crs_source"""

        axes_coords = crs_target.transform_points(crs_source, xcoords, ycoords)

        return axes_coords

    def _add_bbox(ax, list_of_patches, paddings={}, bbox_kwargs={}):
        """
        Description:
            This helper function adds a box behind the scalebar:
                Code inspired by: https://stackoverflow.com/questions/17086847/box-around-text-in-matplotlib

        """

        zorder = list_of_patches[0].get_zorder() - 1

        xmin = min([t.get_window_extent().xmin for t in list_of_patches])
        xmax = max([t.get_window_extent().xmax for t in list_of_patches])
        ymin = min([t.get_window_extent().ymin for t in list_of_patches])
        ymax = max([t.get_window_extent().ymax for t in list_of_patches])

        xmin, ymin = ax.transData.inverted().transform((xmin, ymin))
        xmax, ymax = ax.transData.inverted().transform((xmax, ymax))

        xmin = xmin - ((xmax - xmin) * paddings["xmin"])
        ymin = ymin - ((ymax - ymin) * paddings["ymin"])

        xmax = xmax + ((xmax - xmin) * paddings["xmax"])
        ymax = ymax + ((ymax - ymin) * paddings["ymax"])

        width = xmax - xmin
        height = ymax - ymin

        # Setting xmin according to height
        rect = patches.Rectangle(
            (xmin, ymin),
            width,
            height,
            facecolor=bbox_kwargs["facecolor"],
            edgecolor=bbox_kwargs["edgecolor"],
            alpha=bbox_kwargs["alpha"],
            transform=ax.projection,
            fill=True,
            clip_on=False,
            zorder=zorder,
        )

        ax.add_patch(rect)
        return ax

    # --------------------------------------------------------------------------

    old_proj = ax.projection
    ax.projection = ccrs.PlateCarree()

    # Set a planar (metric) projection for the centroid of a given axes projection:
    # First get centroid lon and lat coordinates:

    lon_0, lon_1, lat_0, lat_1 = ax.get_extent(ax.projection.as_geodetic())

    central_lon = np.mean([lon_0, lon_1])
    central_lat = np.mean([lat_0, lat_1])

    # Second: set the planar (metric) projection centered in the centroid of the axes;
    # Centroid coordinates must be in lon/lat.
    proj = ccrs.EquidistantConic(central_longitude=central_lon,
                                 central_latitude=central_lat)

    # fetch axes coordinates in meters
    x0, x1, y0, y1 = ax.get_extent(proj)
    ymean = np.mean([y0, y1])

    # set target rectangle in-visible-area (aka 'Axes') coordinates
    axfrac_ini, axfrac_final = at_x
    ayfrac_ini, ayfrac_final = at_y

    # choose exact X points as sensible grid ticks with Axis 'ticker' helper
    converted_metric_distance = convert_SI(metric_distance, unit, "m")

    xcoords = []
    ycoords = []
    xlabels = []
    for i in range(0, 1 + max_stripes):
        dx = (converted_metric_distance * i) + x0
        xlabels.append(metric_distance * i)
        xcoords.append(dx)
        ycoords.append(ymean)

    # Convertin to arrays:
    xcoords = np.asanyarray(xcoords)
    ycoords = np.asanyarray(ycoords)

    # Ensuring that the coordinate projection is in degrees:
    x_targets, y_targets, z_targets = _crs_coord_project(
        ax.projection, xcoords, ycoords, proj).T
    x_targets = [x + (axfrac_ini * (lon_1 - lon_0)) for x in x_targets]

    # Checking x_ticks in axes projection coordinates
    # print('x_targets', x_targets)

    # Setting transform for plotting
    transform = ax.projection

    # grab min+max for limits
    xl0, xl1 = x_targets[0], x_targets[-1]

    # calculate Axes Y coordinates of box top+bottom
    yl0, yl1 = [
        lat_0 + ay_frac * (lat_1 - lat_0)
        for ay_frac in [ayfrac_ini, ayfrac_final]
    ]

    # calculate Axes Y distance of ticks + label margins
    y_margin = (yl1 - yl0) * ytick_label_margins

    # fill black/white 'stripes' and draw their boundaries
    fill_colors = ["black", "white"]
    i_color = 0

    filled_boxs = []
    for xi0, xi1 in zip(x_targets[:-1], x_targets[1:]):
        # fill region
        filled_box = plt.fill(
            (xi0, xi1, xi1, xi0, xi0),
            (yl0, yl0, yl1, yl1, yl0),
            fill_colors[i_color],
            transform=transform,
            clip_on=False,
            zorder=zorder,
        )

        filled_boxs.append(filled_box[0])

        # draw boundary
        plt.plot(
            (xi0, xi1, xi1, xi0, xi0),
            (yl0, yl0, yl1, yl1, yl0),
            "black",
            clip_on=False,
            transform=transform,
            zorder=zorder,
        )

        i_color = 1 - i_color

    # adding boxes
    _add_bbox(ax, filled_boxs, bbox_kwargs=bbox_kwargs, paddings=paddings)

    # add short tick lines
    for x in x_targets:
        plt.plot(
            (x, x),
            (yl0, yl0 - y_margin),
            "black",
            transform=transform,
            zorder=zorder,
            clip_on=False,
        )

    # add a scale legend unit
    font_props = mfonts.FontProperties(size=fontsize, weight=font_weight)

    plt.text(
        0.5 * (xl0 + xl1),
        yl1 + y_margin,
        unit,
        color="black",
        verticalalignment="bottom",
        horizontalalignment="center",
        fontproperties=font_props,
        transform=transform,
        clip_on=False,
        zorder=zorder,
    )

    # add numeric labels
    for x, xlabel in zip(x_targets, xlabels):
        # print("Label set in: ", x, yl0 - 2 * y_margin)
        plt.text(
            x,
            yl0 - 2 * y_margin,
            "{:g}".format((xlabel)),
            verticalalignment="top",
            horizontalalignment="center",
            fontproperties=font_props,
            transform=transform,
            rotation=rotation,
            clip_on=False,
            zorder=zorder + 1,
            # bbox=dict(facecolor='red', alpha=0.5) # this would add a box only around the xticks
        )

    # Adjusting figure borders to ensure that the scalebar is within its limits
    ax.projection = old_proj
    ax.get_figure().canvas.draw()
コード例 #23
0
plt.show()

# ~ #***********************************************************************
# ~ #                  LISTE DES PROJECTIONS
# ~ #***********************************************************************
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16, 18))
fig.suptitle('Projections', fontsize=20, y=0.92)

projections = {
    'PlateCarree': ccrs.PlateCarree(),
    'AlbersEqualArea': ccrs.AlbersEqualArea(),
    'AzimuthalEquidistant': ccrs.AzimuthalEquidistant(),
    'EquidistantConic': ccrs.EquidistantConic(),
    'LambertConformal': ccrs.LambertConformal(),
    'LambertCylindrical': ccrs.LambertCylindrical(),
    'Mercator': ccrs.Mercator(),
    'Miller': ccrs.Miller(),
    'Mollweide': ccrs.Mollweide(),
    'Orthographic': ccrs.Orthographic(),
    'Robinson': ccrs.Robinson(),
    'Sinusoidal': ccrs.Sinusoidal(),
    'Stereographic': ccrs.Stereographic(),
    'TransverseMercator': ccrs.TransverseMercator(),
    'InterruptedGoodeHomolosine': ccrs.InterruptedGoodeHomolosine(),
    'RotatedPole': ccrs.RotatedPole(),
    'OSGB': ccrs.OSGB(),
    'EuroPP': ccrs.EuroPP(),
    'Geostationary': ccrs.Geostationary(),