Example #1
0
def drawmap_Moll():
    ax = plt.axes(projection=ccrs.Mollweide())
    ax.coastlines()
    ax.set_xticks(range(-180,180,60),crs=ccrs.Mollweide())
    ax.set_yticks(range(-90,90,30),crs=ccrs.Mollweide())

    return ax
Example #2
0
def test_offset():
    crs = ccrs.Mollweide()
    crs_offset = ccrs.Mollweide(false_easting=1234, false_northing=-4321)
    other_args = {'a=6378137.0', 'lon_0=0', 'x_0=1234', 'y_0=-4321'}
    check_proj_params('moll', crs_offset, other_args)
    assert tuple(np.array(crs.x_limits) + 1234) == crs_offset.x_limits
    assert tuple(np.array(crs.y_limits) - 4321) == crs_offset.y_limits
Example #3
0
def map1(z1, lons, lats):
    import cartopy
    from mpl_toolkits.axes_grid1 import AxesGrid
    proj = ccrs.Mollweide()
    dproj = ccrs.PlateCarree()
    cv = np.arange(-4, 5, 1)
    vm = 4
    ax = plt.axes(projection=ccrs.Mollweide())
    ax.coastlines(resolution='110m')
    ax.gridlines()
    plt.contourf(lons,
                 lats,
                 z1,
                 levels=cv,
                 cmap='RdBu_r',
                 transform=dproj,
                 extend='both')
    #    plt.pcolormesh(lons, lats, z1,vmin=-1*vm,vmax=vm, cmap='RdBu_r',transform=dproj)
    #plt.contourf(lons, lats, sst, levels=cv, extend='both', cmap='RdBu', transform=dproj)
    plt.colorbar()
    ax.add_feature(cartopy.feature.LAND,
                   zorder=0,
                   edgecolor='black',
                   color='white')
    return
Example #4
0
    def test_globe(self):
        # Ensure the globe affects output.
        rugby_globe = ccrs.Globe(semimajor_axis=9000000,
                                 semiminor_axis=9000000,
                                 ellipse=None)
        footy_globe = ccrs.Globe(semimajor_axis=1000000,
                                 semiminor_axis=1000000,
                                 ellipse=None)

        rugby_moll = ccrs.Mollweide(globe=rugby_globe)
        footy_moll = ccrs.Mollweide(globe=footy_globe)

        rugby_pt = rugby_moll.transform_point(
            10,
            10,
            rugby_moll.as_geodetic(),
        )
        footy_pt = footy_moll.transform_point(
            10,
            10,
            footy_moll.as_geodetic(),
        )

        assert_arr_almost_eq(rugby_pt, (1400915, 1741319), decimal=0)
        assert_arr_almost_eq(footy_pt, (155657, 193479), decimal=0)
Example #5
0
def main():
    # Load data
    filepath = iris.sample_data_path("orca2_votemper.nc")
    cube = iris.load_cube(filepath)

    # Choose plot projections
    projections = {}
    projections["Mollweide"] = ccrs.Mollweide()
    projections["PlateCarree"] = ccrs.PlateCarree()
    projections["NorthPolarStereo"] = ccrs.NorthPolarStereo()
    projections["Orthographic"] = ccrs.Orthographic(central_longitude=-90,
                                                    central_latitude=45)

    pcarree = projections["PlateCarree"]
    # Transform cube to target projection
    new_cube, extent = iris.analysis.cartography.project(cube,
                                                         pcarree,
                                                         nx=400,
                                                         ny=200)

    # Plot data in each projection
    for name in sorted(projections):
        fig = plt.figure()
        fig.suptitle("ORCA2 Data Projected to {}".format(name))
        # Set up axes and title
        ax = plt.subplot(projection=projections[name])
        # Set limits
        ax.set_global()
        # plot with Iris quickplot pcolormesh
        qplt.pcolormesh(new_cube)
        # Draw coastlines
        ax.coastlines()

        iplt.show()
Example #6
0
def test_grid():
    # USGS Professional Paper 1395, pg 252, Table 42
    globe = ccrs.Globe(ellipse=None,
                       semimajor_axis=0.5**0.5, semiminor_axis=0.5**0.5)
    moll = ccrs.Mollweide(globe=globe)
    geodetic = moll.as_geodetic()

    other_args = {'a=0.7071067811865476', 'b=0.7071067811865476', 'lon_0=0'}
    check_proj_params('moll', moll, other_args)

    assert_almost_equal(np.array(moll.x_limits),
                        [-2, 2])
    assert_almost_equal(np.array(moll.y_limits),
                        [-1, 1])

    lats = np.arange(0, 91, 5)[::-1]
    lons = np.full_like(lats, 90)
    result = moll.transform_points(geodetic, lons, lats)

    expected_x = np.array([
        0.00000, 0.20684, 0.32593, 0.42316, 0.50706, 0.58111, 0.64712, 0.70617,
        0.75894, 0.80591, 0.84739, 0.88362, 0.91477, 0.94096, 0.96229, 0.97882,
        0.99060, 0.99765, 1.00000,
    ])
    assert_almost_equal(result[:, 0], expected_x, decimal=5)

    expected_y = np.array([
        1.00000, 0.97837, 0.94539, 0.90606, 0.86191, 0.81382, 0.76239, 0.70804,
        0.65116, 0.59204, 0.53097, 0.46820, 0.40397, 0.33850, 0.27201, 0.20472,
        0.13681, 0.06851, 0.00000,
    ])
    assert_almost_equal(result[:, 1], expected_y, decimal=5)
def plot_sphere_density(lonlat, probs, npts, uniform=False):
    # lon in [0,2pi], lat in [0,pi]
    fig = plt.figure(figsize=(3, 2), dpi=200)
    proj = ccrs.Mollweide()
    ax = fig.add_subplot(111, projection=proj)
    lon, lat = lonlat[:, 0], lonlat[:, 1]
    lon = lon.cpu().numpy().reshape(npts, npts)
    lat = lat.cpu().numpy().reshape(npts, npts)
    lon -= np.pi
    lat -= np.pi / 2
    probs = probs.cpu().numpy().reshape(npts, npts)
    if not uniform:
        ax.pcolormesh(lon * 180 / np.pi,
                      lat * 180 / np.pi,
                      probs,
                      transform=ccrs.PlateCarree(),
                      cmap='magma')
    else:  # uniform color
        colormap = plt.cm.get_cmap('magma')
        norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
        probs[probs > 0] = .5
        ax.pcolormesh(lon * 180 / np.pi,
                      lat * 180 / np.pi,
                      probs,
                      transform=ccrs.PlateCarree(),
                      cmap='magma',
                      norm=norm)

    plt.grid(False)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_global()
Example #8
0
def plot_it(p_, iss_lat, iss_lon, user_lat, user_lon):
    iss_lat = float(iss_lat)
    iss_lon = float(iss_lon)

    ax = plt.axes(projection=ccrs.Mollweide())
    ax.stock_img()
    '''
	print(iss_lat,iss_lon)
	print(type(iss_lat),type(iss_lon))
	print(user_lat,user_lon)'''

    plt.plot(
        [iss_lon],
        [iss_lat],
        color='blue',
        linewidth=2,
        marker='o',
        transform=ccrs.Geodetic(),
    )

    plt.plot(
        [user_lon],
        [user_lat],
        color='green',
        linewidth=2,
        marker='x',
        transform=ccrs.Geodetic(),
    )

    plt.draw()
Example #9
0
def base_map(projection='local', center_lat=0, center_lon=0, extent=None,
             **kwargs):
    """
    Function to plot a basic map which can be used to add data later.
    :param projection: Cartopy projection string
    :param center_lat: Latitude to center map
    :param center_lon: Longitude to center map
    :param extent: List of coordinates for map boundaries
    """
    plt.figure()
    if projection == 'global':
        ax = plt.axes(projection=ccrs.Mollweide(central_longitude=center_lon))
    elif projection == 'local':
        ax = plt.axes(projection=ccrs.AlbersEqualArea(
            central_latitude=center_lat,
            central_longitude=center_lon))
        if extent:
            ax.set_extent(extent)
    elif projection == 'AzimuthalEquidistant':
        ax = plt.axes(projection=ccrs.AzimuthalEquidistant(
                      central_longitude=center_lon,
                      central_latitude=center_lat))
    else:
        print('Projection not supported')
    ax.coastlines()
    ax.add_feature(cfeature.LAND)
    ax.add_feature(cfeature.BORDERS, linestyle='-')
    return ax
Example #10
0
    def test_simple(self):
        # First sub-plot
        plt.subplot(221)
        plt.title('Default')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Second sub-plot
        plt.subplot(222, projection=ccrs.Mollweide(central_longitude=120))
        plt.title('Molleweide')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Third sub-plot (the projection part is redundant, but a useful
        # test none-the-less)
        ax = plt.subplot(223, projection=iplt.default_projection(self.cube))
        plt.title('Native')
        iplt.contour(self.cube)
        ax.coastlines()

        # Fourth sub-plot
        ax = plt.subplot(2, 2, 4, projection=ccrs.PlateCarree())
        plt.title('PlateCarree')
        iplt.contourf(self.cube)
        ax.coastlines()

        self.check_graphic()
    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
Example #12
0
def plot_synthetic_poles(ax=None, title=''):
    if ax is None:
        if proj_type == 'M':
            myax = plt.axes(projection=ccrs.Mollweide(200. - lon_shift))
        elif proj_type == 'O':
            myax = plt.axes(
                projection=ccrs.Orthographic(200. - lon_shift, 30.))
    else:
        myax = ax

    myax.gridlines()

    colorcycle = itertools.cycle(colors)
    lons, lats, ages = path.compute_synthetic_poles(n=100)
    for i in range(len(poles)):
        c = colorcycle.next()
        poles[i].plot(ax, color=c)
        myax.scatter(lons[:, i],
                     lats[:, i],
                     color=c,
                     transform=ccrs.PlateCarree())

    if title != '':
        myax.set_title(title)

    if ax is None:
        plt.savefig("keweenawan_poles_" + str(n_euler_rotations) + ".pdf")
Example #13
0
def plot_tomo_map(sph_file,
                  depth,
                  vmin=-2.0,
                  vmax=2.0,
                  lmin=0,
                  lmax=40,
                  contour_levels=20):
    sph_splines = read_sph(sph_file, lmin, lmax)
    spl_vals = find_spl_vals(depth)
    map_dv = 0.0

    fig = plt.figure(figsize=[8, 5])
    tomo_map = plt.subplot(1, 1, 1, projection=ccrs.Mollweide(180))

    for i, sph_spline in enumerate(sph_splines):
        grid = sph_spline.expand()
        map_dv += spl_vals[i] * grid.data

    lons, lats = np.meshgrid(grid.lons(), grid.lats())
    cf = tomo_map.pcolormesh(grid.lons(),
                             grid.lats(),
                             map_dv * 100.0,
                             transform=ccrs.PlateCarree(),
                             cmap='jet_r',
                             vmin=vmin,
                             vmax=vmax)

    tomo_map.coastlines(zorder=99)
    plt.colorbar(cf, fraction=0.02, pad=0.02, label='$\delta$Vs (%)')
    plt.title('depth = {} km, lmin = {}, lmax = {}'.format(depth, lmin, lmax))
    plt.show()
Example #14
0
def plot_nino_regions():

    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs

    fig = plt.figure(figsize=(12, 8))
    ax = plt.axes(projection=ccrs.Mollweide(-160))
    #ax.coastlines();
    ax.stock_img()
    ax.gridlines()

    from shapely.geometry import Polygon
    nino12 = Polygon([(-90, 0), (-80, 0), (-80, -10), (-90, -10)])
    nino3 = Polygon([(-150, 5), (-90, 5), (-90, -5), (-150, -5)])
    nino34 = Polygon([(-170, 5), (-120, 5), (-120, -5), (-170, -5)])
    nino4 = Polygon([(-200, 5), (-150, 5), (-150, -5), (-200, -5)])
    ninos = [[x] for x in [nino12, nino3, nino34, nino4]]

    color = ['none', "orange", 'none', "green"]
    for e, nino in enumerate(ninos):
        ax.add_geometries(nino,
                          ccrs.PlateCarree(),
                          facecolor=color[e],
                          linewidth=2,
                          edgecolor='k',
                          alpha=0.6,
                          label="sd")
    ax.text(-88, 2, "Nino\n1+2", transform=ccrs.PlateCarree())
    ax.text(-155, 7, "Nino 3.4", transform=ccrs.PlateCarree())
    ax.text(-125, 7, "Nino 3", transform=ccrs.PlateCarree())
    ax.text(-180, 7, "Nino 4", transform=ccrs.PlateCarree())
    ax.set_extent([-250, -40, -60, 60], crs=ccrs.PlateCarree())
Example #15
0
def plot_global_map(map_in,
                    proj='Mollweide',
                    vmin_in=-999.0,
                    vmax_in=999.0,
                    lower_zero=False,
                    title='Plot',
                    units=' ',
                    central_longitude=90.0,
                    ct_name='jet'):

    import matplotlib.pyplot as plt
    import numpy as np
    import cartopy.crs as ccrs

    figsize = (8.0, 4.0)
    fig = plt.figure(figsize=figsize)

    if proj == 'Rectangular':
        ax = plt.axes(projection=ccrs.PlateCarree(
            central_longitude=central_longitude))
    elif proj == 'Mollweide':
        ax = plt.axes(projection=ccrs.Mollweide(
            central_longitude=central_longitude))
    else:
        print 'Can not find projection ' + proj
        print 'Setting proj to rectangular'
        proj = 'Rectangular'
        ax = plt.axes(projection=ccrs.PlateCarree(
            central_longitude=central_longitude))

    nlats, nlons = map_in.shape
    lats = np.rad2deg(np.linspace(-np.pi / 2, np.pi / 2, nlats + 1))
    lons = np.rad2deg(np.linspace(0.0, 2.0 * np.pi, nlons + 1))

    acmap = plt.get_cmap(ct_name)
    [vmin, vmax] = bounds_pretty(map_in, vmin_in, vmax_in, lower_zero)

    if proj == 'Rectangular':
        p = plt.pcolormesh(lons,
                           lats,
                           map_in,
                           cmap=acmap,
                           transform=ccrs.PlateCarree(),
                           vmin=vmin,
                           vmax=vmax)
    elif proj == 'Mollweide':
        p = plt.pcolormesh(lons,
                           lats,
                           map_in,
                           cmap=acmap,
                           transform=ccrs.PlateCarree(),
                           vmin=vmin,
                           vmax=vmax)

    ax.coastlines()
    ax.set_global()
    cb = plt.colorbar(p, orientation='horizontal', shrink=0.6)
    cb.ax.set_title(title)
    plt.show()
Example #16
0
def make_map_base(projection="Robinson",
                  proj_args={},
                  coastlines='k',
                  land='#964B00',
                  ocean='#006994',
                  statelines=None,
                  natborders='gray',
                  lakelines=None,
                  lakes='#006994',
                  **kwargs):
    """Plot gridded data on map.
    Optionally add pointdata sequence of (lon,lat,data)."""
    cl = proj_args.get('central_longitude', 180)
    extent = proj_args.get('extent', None)
    if projection.lower() in ['mollweide']:
        proj = ccrs.Mollweide(central_longitude=cl)
    elif projection.lower() in ['platecarree', 'flat']:
        proj = ccrs.PlateCarree(central_longitude=cl)
    elif projection.lower() in ['eckertiv']:
        proj = ccrs.EckertIV(central_longitude=cl)
    elif projection.lower() in ['robinson']:
        proj = ccrs.Robinson(central_longitude=cl)
    else:
        print("IMPLEMENT PROJECTION!")

    figsize = kwargs.get('figsize', (12, 8))
    fig = plt.figure(figsize=figsize)
    ax = plt.axes(projection=proj)  # ccrs.PlateCarree())

    if coastlines is not None:
        ax.coastlines(color=coastlines)
    # ax.gridlines()
    if statelines is not None:
        ax.add_feature(
            cfeature.NaturalEarthFeature('cultural',
                                         'admin_1_states_provinces_lines',
                                         '50m',
                                         edgecolor=statelines,
                                         facecolor='none',
                                         linestyle='-'))
    if natborders is not None:
        ax.add_feature(cfeature.BORDERS, color=natborders)
    if (lakelines is not None) or (lakes is not None):
        ax.add_feature(cfeature.LAKES, edgecolor=lakelines, facecolor=lakes)
    if land is not None:
        # np.array( [0.9375, 0.9375, 0.859375]))
        ax.add_feature(cfeature.LAND, color=land)
    if ocean is not None:
        ax.add_feature(cfeature.OCEAN, color=ocean)

    ftitle = kwargs.get('title', '')
    ax.set_title(ftitle, fontsize=15)

    if extent is not None:
        ax.set_extent(extent)
        ratio = abs((extent[0] - extent[1]) / (extent[2] - extent[3]))
    else:
        ratio = 1.0
    return ax
Example #17
0
def test_sphere_globe():
    globe = ccrs.Globe(semimajor_axis=1000, ellipse=None)
    moll = ccrs.Mollweide(globe=globe)
    other_args = {'a=1000', 'lon_0=0'}
    check_proj_params('moll', moll, other_args)

    assert_almost_equal(moll.x_limits, [-2828.4271247, 2828.4271247])
    assert_almost_equal(moll.y_limits, [-1414.2135624, 1414.2135624])
Example #18
0
def mollweide_data_dist_sphere(lat, lon, fname=None, Title=None):
    fig = plt.figure()
    ax = plt.axes(projection=ccrs.Mollweide(central_longitude=0))
    ax.set_global()
    ax.coastlines()
    ax.scatter(lon, lat, transform=ccrs.PlateCarree())
    plt.tight_layout()
    plt.show()
Example #19
0
def test_basic_click_projection_kwarg():
    import cartopy.crs as ccrs
    """
	Test init without fig
	"""
    fig = plt.figure()
    click_map = survey.click_map(fig=fig, projection=ccrs.Mollweide())
    return plt.gcf()
Example #20
0
def test_eccentric_globe():
    globe = ccrs.Globe(semimajor_axis=1000, semiminor_axis=500, ellipse=None)
    moll = ccrs.Mollweide(globe=globe)
    other_args = {'a=1000', 'b=500', 'lon_0=0'}
    check_proj4_params(moll, other_args)

    assert_almost_equal(np.array(moll.x_limits), [-2828.4271247, 2828.4271247])
    assert_almost_equal(np.array(moll.y_limits),
                        [-1414.2135623731, 1414.2135623731])
Example #21
0
File: vlbi.py Project: mfkiwl/where
def _matplotlib_map(dset):
    # Local imports since only this function uses plotting
    import cartopy.crs as ccrs
    from matplotlib import cm
    import matplotlib.pyplot as plt

    stations = dset.unique("station")
    baselines = dset.unique("baseline")
    b_width = {b: dset.num(baseline=b) / dset.num_obs * 40 for b in baselines}
    s_size = [int(dset.num(station=s) / dset.num_obs * 400) for s in stations]

    lat = np.degrees([dset.meta[station]["latitude"] for station in stations])
    lon = np.degrees([dset.meta[station]["longitude"] for station in stations])

    rms = [dset.rms("residual", station=station)
           for station in stations] if "residual" in dset._fields else None
    plt.figure()
    ax = plt.axes(projection=ccrs.Mollweide())
    ax.set_global()
    ax.coastlines()
    cmap = cm.get_cmap(config.there.colormap.str)

    for baseline in baselines:
        sta_1, _, sta_2 = baseline.partition("/")
        sta_1_lon = np.degrees(dset.meta[sta_1]["longitude"])
        sta_2_lon = np.degrees(dset.meta[sta_2]["longitude"])
        sta_1_lat = np.degrees(dset.meta[sta_1]["latitude"])
        sta_2_lat = np.degrees(dset.meta[sta_2]["latitude"])
        b_rms = dset.rms(
            "residual", baseline=baseline) if "residual" in dset._fields else 0
        color = cmap(b_rms)
        plt.plot(
            [sta_1_lon, sta_2_lon],
            [sta_1_lat, sta_2_lat],
            c=color,
            linestyle="--",
            linewidth=b_width[baseline],
            transform=ccrs.Geodetic(),
            zorder=0,
        )
    plt.scatter(lon,
                lat,
                c=rms,
                transform=ccrs.PlateCarree(),
                cmap=cmap,
                s=s_size,
                zorder=10)
    plt.title(f"{dset.meta['input']['session_code']}")
    plt.figtext(0.99,
                0.01,
                "Size: number of observations",
                horizontalalignment="right")
    if rms is not None:
        cbar = plt.colorbar()
        cbar.set_label("RMS of residual [m]")

    plt.show()
Example #22
0
def test_default():
    moll = ccrs.Mollweide()
    other_args = {'a=6378137.0', 'lon_0=0'}
    check_proj_params('moll', moll, other_args)

    assert_almost_equal(np.array(moll.x_limits),
                        [-18040095.6961473, 18040095.6961473])
    assert_almost_equal(np.array(moll.y_limits),
                        [-9020047.8480736, 9020047.8480736])
def map_plot(fig: Figure,
             source: Origin,
             reciever: Station,
             position=221,
             resolution="110m"):
    """ Plot a map with a great-circle between source and reciever """
    source_lon, source_lat = source.longitude % 360, source.latitude
    reciever_lon, reciever_lat = reciever.longitude % 360, reciever.latitude

    proj = ccrs.Mollweide(central_longitude=(source_lon + reciever_lon) / 2)
    ax = fig.add_subplot(position, projection=proj)
    ax.set_global()
    borders = cfeature.NaturalEarthFeature(cfeature.BORDERS.category,
                                           cfeature.BORDERS.name,
                                           resolution,
                                           edgecolor='none',
                                           facecolor='none')
    land = cfeature.NaturalEarthFeature(cfeature.LAND.category,
                                        cfeature.LAND.name,
                                        resolution,
                                        edgecolor='face',
                                        facecolor='none')
    ocean = cfeature.NaturalEarthFeature(cfeature.OCEAN.category,
                                         cfeature.OCEAN.name,
                                         resolution,
                                         edgecolor='face',
                                         facecolor='none')
    # ax.set_axis_bgcolor('1.0')
    ax.add_feature(ocean, facecolor='1.0')
    ax.add_feature(land, facecolor='0.8')
    ax.add_feature(borders, edgecolor='0.75')
    ax.coastlines(resolution=resolution, color='0.4')
    ax.gridlines(xlocs=range(-180, 181, 30), ylocs=range(-90, 91, 30))

    source_scatter = ax.scatter(source_lon,
                                source_lat,
                                marker="o",
                                s=100,
                                c="red",
                                zorder=10,
                                transform=ccrs.Geodetic(),
                                label="Source")
    reciever_scatter = ax.scatter(reciever_lon,
                                  reciever_lat,
                                  marker="v",
                                  s=100,
                                  c="blue",
                                  zorder=10,
                                  transform=ccrs.Geodetic(),
                                  label="Receiver")
    # Plot great circle
    ax.plot([source_lon, reciever_lon], [source_lat, reciever_lat],
            "k",
            transform=ccrs.Geodetic())
    ax.legend()

    return fig, ax
Example #24
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)
Example #25
0
 def create_map(self, name, lon=0):
     if name == 'mollweide':
         ax = plt.axes(projection=ccrs.Mollweide(central_longitude=lon))
     elif name == 'robinson':
         ax = plt.axes(projection=ccrs.Robinson(central_longitude=lon))
     else:  #'rectangular' and by default
         ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=lon))
     ax.gridlines()
     ax.set_global()
     return ax
Example #26
0
def test_central_longitude(lon):
    moll = ccrs.Mollweide(central_longitude=lon)
    other_args = {'a=6378137.0', 'lon_0={}'.format(lon)}
    check_proj_params('moll', moll, other_args)

    assert_almost_equal(np.array(moll.x_limits),
                        [-18040095.6961473, 18040095.6961473],
                        decimal=5)
    assert_almost_equal(np.array(moll.y_limits),
                        [-9020047.8480736, 9020047.8480736])
Example #27
0
def test_gshhs():
    ax = plt.axes(projection=ccrs.Mollweide())
    ax.set_extent([138, 142, 32, 42], ccrs.Geodetic())

    ax.stock_img()
    # Draw coastlines.
    ax.add_feature(cfeature.GSHHSFeature('coarse', edgecolor='red'))
    # Draw higher resolution lakes (and test overriding of kwargs)
    ax.add_feature(cfeature.GSHHSFeature('low', levels=[2], facecolor='green'),
                   facecolor='blue')
def main():
    ax = plt.axes(projection=ccrs.Mollweide())

    lons, lats, data = sample_data()

    ax.contourf(lons, lats, data,
                transform=ccrs.PlateCarree(),
                cmap='spectral')
    ax.coastlines()
    ax.set_global()
    plt.show()
def spherical_plot(time_temp):
    # projections: https://scitools.org.uk/cartopy/docs/latest/crs/projections.html
    # PlateCarree(), Orthographic(-80, 35)
    p = time_temp.isel(time=0).plot(
        subplot_kws=dict(projection=ccrs.Mollweide(), facecolor="gray"),
        transform=ccrs.PlateCarree(),
    )
    p.axes.set_global()
    p.axes.coastlines()
    plt.savefig(f"{savepath}{output}_sphere.png")
    plt.close()
Example #30
0
def test_plot_regions_projection():

    # if none is given -> no projection
    with figure_context():
        ax = r1.plot_regions(subsample=False)
        assert not hasattr(ax, "projection")

    # projection given with axes is respected
    with figure_context() as f:
        ax = f.subplots(subplot_kw=dict(projection=ccrs.Mollweide()))
        ax = r1.plot_regions(subsample=False, ax=ax)
        assert isinstance(ax.projection, ccrs.Mollweide)