Ejemplo n.º 1
0
def test_gridmapdisplay_fancy(outfile=None):
    # test a bunch of GridMapDisplay functionaliy
    grid = pyart.testing.make_target_grid()
    display = pyart.graph.GridMapDisplay(grid)
    fig = plt.figure(1, figsize=[25., 17.])
    projection = ccrs.Mercator()

    ax1 = plt.subplot(331, projection=projection)
    display.plot_grid('reflectivity',
                      vmin=-5.,
                      vmax=35.,
                      mask_outside=True,
                      axislabels=('foo', 'bar'),
                      axislabels_flag=True,
                      title='Special title')
    display.plot_crosshairs(color='b')

    ax2 = plt.subplot(332, projection=projection)
    display.plot_grid('reflectivity', axislabels_flag=True)

    ax3 = plt.subplot(333)
    display.plot_colorbar()

    ax4 = plt.subplot(334)
    display.plot_latitude_slice('reflectivity', mask_outside=True)

    ax5 = plt.subplot(335)
    display.plot_latitude_slice('reflectivity', title='Lat title')

    ax6 = plt.subplot(336)
    grid.fields['reflectivity']['valid_min'] = 0
    grid.fields['reflectivity']['valid_max'] = 30
    display.plot_longitude_slice('reflectivity', mask_outside=True)

    ax7 = plt.subplot(337)
    display.plot_longitude_slice('reflectivity', title='Lon title')

    ax8 = plt.subplot(338)
    del display.grid.fields['reflectivity']['long_name']
    display.plot_colorbar()

    if outfile:
        fig.savefig(outfile)
Ejemplo n.º 2
0
 def test_non_default(self):
     """Test that the __repr__ returns the expected string with defaults."""
     plugin = NeighbourSelection(
         land_constraint=True,
         minimum_dz=True,
         search_radius=1000,
         site_coordinate_system=ccrs.Mercator(),
         site_x_coordinate="x_axis",
         site_y_coordinate="y_axis",
         node_limit=100,
     )
     result = str(plugin)
     msg = (
         "<NeighbourSelection: land_constraint: True, minimum_dz: True,"
         " search_radius: 1000, site_coordinate_system: <class "
         "'cartopy.crs.Mercator'>, site_x_coordinate:x_axis, "
         "site_y_coordinate: y_axis, node_limit: 100>"
     )
     self.assertEqual(result, msg)
Ejemplo n.º 3
0
def test_pcolormesh_wrap_set_array():
    x = np.linspace(0, 360, 73)
    y = np.linspace(-87.5, 87.5, 36)
    X, Y = np.meshgrid(*[np.deg2rad(c) for c in (x, y)])
    Z = np.cos(Y) + 0.375 * np.sin(2. * X)
    Z = Z[:-1, :-1]
    ax = plt.axes(projection=ccrs.Mercator())
    norm = plt.Normalize(np.min(Z), np.max(Z))
    ax.coastlines()
    # Start off with bad data
    coll = ax.pcolormesh(x,
                         y,
                         np.ones(Z.shape),
                         norm=norm,
                         transform=ccrs.PlateCarree(),
                         snap=False)
    # Now update the plot with the set_array method
    coll.set_array(Z.ravel())
    return ax.figure
Ejemplo n.º 4
0
def test_spectral():
    # setup mercator map projection.
    fig = plt.figure()
    ax = plt.axes(projection=ccrs.Mercator(central_longitude=0))
    cs = ax.contourf(lons,
                     lats,
                     data,
                     15,
                     cmap=plt.cm.jet,
                     transform=ccrs.PlateCarree())
    ax.coastlines()
    gl = ax.gridlines(draw_labels=True)
    gl.right_labels = False
    gl.top_labels = False
    plt.colorbar(cs, shrink=0.9)
    plt.title(repr(g.level) + ' ' + g.typeOfLevel + ' ' + g.name +
              ' from Spherical Harmonic Coeffs',
              fontsize=9)
    return fig
Ejemplo n.º 5
0
def plot_grid(longitude,
              latitude,
              int_lon,
              int_lat,
              g,
              cmap='viridis',
              vrange=[None, None],
              crs_latlon=ccrs.PlateCarree(),
              variable_name=''):
    """Plot Grid
    Args:
        int_lon: (M,N) array of longitude grid
        int_lat: (M,N) array of latitude grid
        g: (M,N) grid to be shown
        cmap: colormap
        vrange: Ranges for grid to be shown i.e [0,35]
        crs_latlon:
        variable_name:
    Returns:
        Map with interpolated values
    """

    fig = plt.figure(figsize=(12, 14))
    extent = [longitude[0], longitude[1], latitude[0], latitude[1]]
    central_lon = np.mean(extent[:2])
    central_lat = np.mean(extent[2:])

    ax = plt.axes(projection=ccrs.Mercator(central_lon))

    geo_map(ax)
    cf = plt.contourf(int_lon,
                      int_lat,
                      g,
                      100,
                      transform=ccrs.PlateCarree(),
                      cmap=cmap)
    cb = fig.colorbar(cf,
                      ax=ax,
                      orientation='horizontal',
                      ticklocation='auto',
                      pad=0.05)
    cb.ax.set_title(variable_name)
Ejemplo n.º 6
0
def plot_mercator(data_dict, extent_coords):

    globe = ccrs.Globe(semimajor_axis=data_dict['semi_major_axis'],
                       semiminor_axis=data_dict['semi_minor_axis'],
                       flattening=None,
                       inverse_flattening=data_dict['inv_flattening'])

    ext_lats = [extent_coords[0][0], extent_coords[1][0]]
    ext_lons = [extent_coords[0][1], extent_coords[1][1]]

    Xs, Ys = georeference(data_dict['x'], data_dict['y'], data_dict['lon_0'],
                          data_dict['height'], data_dict['sweep_ang_axis'])

    fig = plt.figure(figsize=(10, 5))

    ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator(globe=globe))

    states = NaturalEarthFeature(category='cultural',
                                 scale='50m',
                                 facecolor='none',
                                 name='admin_1_states_provinces_shp')

    ax.add_feature(states, linewidth=.8, edgecolor='black')

    ax.set_extent([min(ext_lons),
                   max(ext_lons),
                   min(ext_lats),
                   max(ext_lats)],
                  crs=ccrs.PlateCarree())

    cmesh = plt.pcolormesh(Xs,
                           Ys,
                           data_dict['data'],
                           vmin=0,
                           vmax=350,
                           transform=ccrs.PlateCarree(),
                           cmap=cm.jet)
    cbar = plt.colorbar(cmesh, fraction=0.046, pad=0.04)

    plt.tight_layout()
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()
Ejemplo n.º 7
0
def plotter(x, lat, lon, u, v, cmap, clevs, bati, lat_i, lat_f, lon_i, lon_f,
            cbar_label):
    import cartopy.crs as ccrs
    from cartopy.feature import NaturalEarthFeature
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import matplotlib.gridspec as gridspec
    import shapely.geometry as sgeom
    import numpy as np
    import xarray

    x_o, y_o = np.meshgrid(u.longitude, v.latitude)
    x1, y1 = np.meshgrid(lon, lat)
    x_b, y_b = np.meshgrid(bati['x'], bati['y'])

    fig = plt.figure(figsize=(10,12))
    ax = fig.add_subplot(111, projection=ccrs.Mercator())

    ax.set_extent([lon_i, lon_f, lat_f, lat_i], crs=ccrs.PlateCarree())
    tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white')
    ax.add_feature(tierra)
    ax.coastlines(resolution='50m')
    gl = ax.gridlines(crs=ccrs.PlateCarree(central_longitude=0),
                      draw_labels=True, color='white', linestyle='--', linewidth=.3)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    box = sgeom.box(minx=-51.67, maxx=-50.33, miny=-34.33, maxy=-34.33)
    ax.add_geometries([box], ccrs.PlateCarree(), facecolor='none',
                      edgecolor='black')

    clr = ax.contourf(x1, y1, x, clevs,
                      transform=ccrs.PlateCarree(), cmap=cmap, extend='both')
    b = ax.contour(x_b, y_b, bati['z'].values, levels=[-1000,-200], colors='k', linewidths=1,
                   linestyles, transform=ccrs.PlateCarree())
    qvr = ax.quiver(x_o, y_o, u.values, v.values,
                    units='xy', scale=0.2/111139, transform=ccrs.PlateCarree())

    cbar = fig.colorbar(clr, ax=ax, shrink=.7)
    cbar.ax.set_ylabel('m/s')
    ax.quiverkey(qvr, .2, 0.8, .2, '0.2 m/s', labelpos='E')

    return fig, ax
Ejemplo n.º 8
0
def main():
    # URL of NASA GIBS
    URL = 'http://gibs.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi'
    wmts = WebMapTileService(URL)

    # Layers for MODIS true color and snow RGB
    layers = [
        'MODIS_Terra_SurfaceReflectance_Bands143',
        'MODIS_Terra_CorrectedReflectance_Bands367'
    ]

    date_str = '2017-12-07'

    # Plot setup
    plot_CRS = ccrs.Mercator()
    geodetic_CRS = ccrs.Geodetic()
    x0, y0 = plot_CRS.transform_point(3.7, 43.9, geodetic_CRS)
    x1, y1 = plot_CRS.transform_point(22.5, 50.8, geodetic_CRS)
    ysize = 8
    xsize = 2 * ysize * (x1 - x0) / (y1 - y0)
    fig = plt.figure(figsize=(xsize, ysize), dpi=100)

    for layer, offset in zip(layers, [0, 0.5]):
        ax = plt.axes([offset, 0, 0.5, 1], projection=plot_CRS)
        ax.set_xlim((x0, x1))
        ax.set_ylim((y0, y1))
        ax.add_wmts(wmts, layer, wmts_kwargs={'time': date_str})
        txt = plt.text(4.7,
                       43.2,
                       wmts[layer].title,
                       fontsize=18,
                       color='wheat',
                       transform=geodetic_CRS)
        txt.set_path_effects(
            [PathEffects.withStroke(linewidth=5, foreground='black')])
        state_boundaries = feat.NaturalEarthFeature(category='cultural',
                                                    name='admin_0_countries',
                                                    scale='10m',
                                                    facecolor='none')
        ax.coastlines(resolution='10m', zorder=1, color='black')
        ax.add_feature(state_boundaries, zorder=1, edgecolor='black')
    plt.show()
Ejemplo n.º 9
0
    def _get_transformation(self):
        """ Get projection and its units to use in cartopy transforamtions from
        current crs

        Returns:
            ccrs.Projection, str
        """
        try:
            if self.crs['init'][-4:] == '3395':
                crs_epsg = ccrs.Mercator()
            else:
                crs_epsg = ccrs.epsg(self.crs['init'][-4:])
        except ValueError:
            crs_epsg = ccrs.PlateCarree()

        try:
            units = crs_epsg.proj4_params['units']
        except KeyError:
            units = '°'
        return crs_epsg, units
Ejemplo n.º 10
0
def plot_data(column, i, title):
    "Plot the column from the DataFrame in the ith subplot"
    crs = ccrs.PlateCarree()
    ax = plt.subplot(2, 2, i, projection=ccrs.Mercator())
    ax.set_title(title)
    # Set vmin and vmax to the extremes of the original data
    maxabs = vd.maxabs(data.air_temperature_c)
    mappable = ax.scatter(
        data.longitude,
        data.latitude,
        c=data[column],
        s=50,
        cmap="seismic",
        vmin=-maxabs,
        vmax=maxabs,
        transform=crs,
    )
    # Set the proper ticks for a Cartopy map
    vd.datasets.setup_texas_wind_map(ax)
    return mappable
Ejemplo n.º 11
0
 def __init__(self,
              proj=None,
              scale='i',
              bbox=None,
              ax=None,
              bg=None,
              borderstyle=None,
              countystyle=None,
              hwystyle=None):
     self.proj = proj or ccrs.Mercator()
     self.bbox = bbox
     if bbox is not None and not isinstance(self.bbox, Geobbox):
         west, east, south, north = self.bbox
         self.bbox = Geobbox(west, east, south, north, self.proj)
     self.bg = bg
     self.scale = scale
     self.borderstyle = borderstyle or MapStyle(1.0, 'gray', 'none', 1.0)
     self.countystyle = countystyle or MapStyle(0.2, 'gray', 'none', 1.0)
     self.hwystyle = hwystyle or MapStyle(0.4, 'brown', 'none', 1.0)
     self._ax = ax
Ejemplo n.º 12
0
def test_projection_object():
    """Test that we can pass a custom map projection."""
    data = xr.open_dataset(get_test_data('narr_example.nc', as_file_obj=False))

    contour = ContourPlot()
    contour.data = data
    contour.level = 700 * units.hPa
    contour.field = 'Temperature'

    panel = MapPanel()
    panel.area = (-110, -60, 25, 55)
    panel.projection = ccrs.Mercator()
    panel.layers = [cfeature.LAKES]
    panel.plots = [contour]

    pc = PanelContainer()
    pc.panel = panel
    pc.draw()

    return pc.figure
Ejemplo n.º 13
0
    def init_plot(self):
        #maplimits = [105, 152, 16, 46]  # [Wlon, Elon, Slat, Nlat]
        self.ax = plt.axes(projection=ccrs.Mercator(central_longitude=180))
        #self.ax.set_extent(maplimits, ccrs.PlateCarree())

        self.readShpFile('./shapefiles/ne_10m_ocean/ne_10m_ocean', 'none', \
            [0.476, 0.661, 0.816, 1], 0)
        self.readShpFile('./shapefiles/ne_10m_admin_0_countries/ne_10m_admin_0_countries', \
            'black', [0.753, 0.753, 0.753, 1], 0.75)
        self.readShpFile('./shapefiles/province/province', 'black', 'none',
                         0.5)
        self.readShpFile('./shapefiles/ne_50m_admin_1_states_provinces/' \
            'ne_50m_admin_1_states_provinces', 'black', 'none', 0.5)
        self.readShpFile('./shapefiles/ne_10m_lakes/ne_10m_lakes', 'black', \
            [0.476, 0.661, 0.816, 1], 0.5)

        gl = self.ax.gridlines(draw_labels=True, color=[0.437, 0.512, 0.565, 1], \
            linestyle='--', zorder=2)
        gl.xlocator = gl.ylocator = mticker.MultipleLocator(5)
        gl.top_labels = False
Ejemplo n.º 14
0
def plot_data(column, i, title):
    "Plot the column from the DataFrame in the ith subplot"
    crs = ccrs.PlateCarree()
    ax = plt.subplot(2, 2, i, projection=ccrs.Mercator())
    ax.set_title(title)
    # Set vmin and vmax to the extremes of the original data
    maxabs = utils.maxabs(data.total_field_anomaly_nt)
    mappable = ax.scatter(
        data.longitude,
        data.latitude,
        c=data[column],
        s=1,
        cmap="seismic",
        vmin=-maxabs,
        vmax=maxabs,
        transform=crs,
    )
    # Set the proper ticks for a Cartopy map
    fetch_data.setup_rio_magnetic_map(ax)
    return mappable
Ejemplo n.º 15
0
    def plot_map(self):
        projection = ccrs.Mercator()
        cmap = "Blues"
        fig, (ax, axr) = plt.subplots(
            nrows=1,
            ncols=2,
            figsize=(9, 8),
            subplot_kw={"projection": projection},
        )

        mindepth = np.min(self.b)
        maxdepth = np.max(self.b)
        h = ax.contourf(
            self.b.lon,
            self.b.lat,
            self.b,
            np.arange(mindepth, maxdepth, 20),
            cmap=cmap,
            vmin=mindepth,
            vmax=maxdepth + 20,
            extend="both",
            zorder=2,
            transform=ccrs.PlateCarree(),
        )
        gl = ax.gridlines(
            crs=ccrs.PlateCarree(),
            draw_labels=True,
            linewidth=0.25,
            color="0.2",
            alpha=0.2,
            zorder=30,
        )
        gl.ylocator = mticker.MaxNLocator(3)
        gl.xlocator = mticker.MaxNLocator(3)
        gl.top_labels = False
        gl.right_labels = False
        lon_formatter = LONGITUDE_FORMATTER
        lat_formatter = LATITUDE_FORMATTER
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)
        return ax
def add_subplot_axes(ax, rect, axisbg='w'):
    fig = plt.gcf()
    box = ax.get_position()
    width = box.width
    height = box.height
    inax_position = ax.transAxes.transform(rect[0:2])
    transFigure = fig.transFigure.inverted()
    infig_position = transFigure.transform(inax_position)
    x = infig_position[0]
    y = infig_position[1]
    width *= rect[2]
    height *= rect[3]  # <= Typo was here
    subax = fig.add_axes([x, y, width, height], projection=ccrs.Mercator())
    x_labelsize = subax.get_xticklabels()[0].get_size()
    y_labelsize = subax.get_yticklabels()[0].get_size()
    x_labelsize *= rect[2]**0.5
    y_labelsize *= rect[3]**0.5
    subax.xaxis.set_tick_params(labelsize=x_labelsize)
    subax.yaxis.set_tick_params(labelsize=y_labelsize)

    x1 = -84.4 - 6.25
    x2 = -84.4 + 6.25
    y1 = 33.7 - 4.5
    y2 = 33.7 + 4
    subax.set_extent([x1, x2, y1, y2], ccrs.Geodetic())
    #subax.coastlines()

    states_provinces = cfeature.NaturalEarthFeature(
        category='cultural',
        name='admin_1_states_provinces_lines',
        scale='50m',
        facecolor='none')
    subax.add_feature(cfeature.COASTLINE, edgecolor='k', linewidth=0.8)
    subax.add_feature(states_provinces,
                      edgecolor='k',
                      linewidth=0.5,
                      alpha=0.5)

    subax.add_feature(shape_feature)

    return subax
Ejemplo n.º 17
0
def get_transformation(crs_in):
    """
    Get projection and its units to use in cartopy transforamtions from
    current crs

    Parameters
    ----------
    crs_in : str
        Current crs

    Returns
    ------
    crs_epsg : ccrs.Projection
    units : str
    """
    try:
        if CRS.from_user_input(crs_in) == CRS.from_user_input('EPSG:3395'):
            crs_epsg = ccrs.Mercator()
        else:
            crs_epsg = ccrs.epsg(CRS.from_user_input(crs_in).to_epsg())
    except ValueError:
        crs_epsg = ccrs.PlateCarree()
    except requests.exceptions.ConnectionError:
        LOGGER.warning('No internet connection.'
                       ' Using projection PlateCarree in plot.')
        crs_epsg = ccrs.PlateCarree()

    try:
        units = (
            crs_epsg.proj4_params.get('units')
            # As of cartopy 0.20 the proj4_params attribute is {} for CRS from an EPSG number
            # (see issue raised https://github.com/SciTools/cartopy/issues/1974
            # and longterm discussion on https://github.com/SciTools/cartopy/issues/813).
            # In these cases the units can be fetched through the method `to_dict`.
            or crs_epsg.to_dict().get('units', '°'))
    except AttributeError:
        # This happens in setups with cartopy<0.20, where `to_dict` is not defined.
        # Officially, we require cartopy>=0.20, but there are still users around that
        # can't upgrade due to https://github.com/SciTools/iris/issues/4468
        units = '°'
    return crs_epsg, units
Ejemplo n.º 18
0
def plot_casts(variable,
               df,
               longitude,
               latitude,
               cmap='viridis',
               vrange=[None, None]):
    """Plot casts
    Args:
        variable: str of oceanographic vairable, i.e. 'Temperature'
        df: Pandas DataFrame from ODP with lat, lon, and variable columns
        longitude: List of min and max longitude, i.e [-10,35]
        latitude: List of min and max latitude, i.e [50,80]
        cmap: colormap specification
        vrange: Ranges for variables to be showsn, i.e. [0,20]
    Returns:
        Map with variable measurments plotted as points
    """
    extent = [longitude[0], longitude[1], latitude[0], latitude[1]]
    central_lon = np.mean(extent[:2])
    central_lat = np.mean(extent[2:])

    fig = plt.figure(figsize=(12, 14))
    ax = plt.axes(projection=ccrs.Mercator(central_lon))
    geo_map(ax)

    cs = plt.scatter(df.lon,
                     df.lat,
                     c=df[variable],
                     cmap=cmap,
                     vmin=vrange[0],
                     vmax=vrange[1],
                     s=10,
                     transform=ccrs.PlateCarree())
    cb = fig.colorbar(cs,
                      ax=ax,
                      orientation='horizontal',
                      ticklocation='auto',
                      pad=0.05)
    cb.ax.set_title('{} ({})'.format(variable,
                                     get_units()[variable]),
                    fontsize=14)
Ejemplo n.º 19
0
def mapplotterUSA(benchmark):

    map = plt.subplot(projection=ccrs.Mercator())

    def map_usa_visualisation(ax):

        shapefile = 'ne_110m_admin_1_states_provinces.shp'
        reader = shapereader.Reader(shapefile)
        adm1_shapes = list(reader.geometries())
        provinces = reader.records()

        #  A province could never have sendertype 0 so colors[0] would not be used
        #  Therefore this color is set to None.
        #         None    blue       green     purple    orange,     red
        colors = [None, '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#e41a1c']

        ax.set_extent([-125, -66.5, 20, 55])
        ax.coastlines(resolution='50m')
        ax.add_feature(cfeature.BORDERS, linestyle='-', alpha=.5)
        ax.add_feature(cfeature.LAND)
        ax.add_feature(cfeature.STATES)
        ax.add_feature(cfeature.OCEAN)
        for i in range(len(adm1_shapes)):
            province = next(provinces)
            ax.add_geometries(adm1_shapes[i],
                              ccrs.PlateCarree(),
                              facecolor=colors[benchmark.get(
                                  province.attributes['name_en'])],
                              edgecolor="black")

        senderA = mpatches.Patch(color='#377eb8', label='Sender type A')
        senderB = mpatches.Patch(color='#4daf4a', label='Sender type B')
        senderC = mpatches.Patch(color='#984ea3', label='Sender type C')
        senderD = mpatches.Patch(color='#ff7f00', label='Sender type D')
        senderE = mpatches.Patch(color='#e41a1c', label='Sender type E')

        plt.title('USA')
        plt.legend(handles=[senderA, senderB, senderC, senderD, senderE])
        pylab.savefig('results/usamap.png')

    map_usa_visualisation(map)
Ejemplo n.º 20
0
    def test_extra_kwargs(self):
        # Check that a projection with non-default values is correctly
        # converted to a cartopy CRS.
        longitude_of_projection_origin = 90.0
        true_scale_lat = 14.0
        ellipsoid = GeogCS(semi_major_axis=6377563.396,
                           semi_minor_axis=6356256.909)

        merc_cs = Mercator(
            longitude_of_projection_origin,
            ellipsoid=ellipsoid,
            standard_parallel=true_scale_lat)

        expected = ccrs.Mercator(
            central_longitude=longitude_of_projection_origin,
            globe=ccrs.Globe(semimajor_axis=6377563.396,
                             semiminor_axis=6356256.909, ellipse=None),
            latitude_true_scale=true_scale_lat)

        res = merc_cs.as_cartopy_crs()
        self.assertEqual(res, expected)
Ejemplo n.º 21
0
def _get_map_info(gd):
    """Get the desired bounds of the map and the figure size (in).

    Args:
        gd (GeoDict): GeoDict to use as basis for map boundaries.

    Returns:
        tuple: xmin,xmax,ymin,ymax Extent of map.
        tuple: Figure size (width,height) in inches.
    """
    # define the map
    # first cope with stupid 180 meridian
    xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax)
    if xmin > xmax:
        xmax = xmax + 360

    center_lon = (xmin + xmax)/2.0

    proj = ccrs.Mercator(central_longitude=center_lon,
                         min_latitude=ymin,
                         max_latitude=ymax,
                         globe=None)
    pproj = pyproj.Proj(proj.proj4_init)
    pxmin, pymin = pproj(xmin, ymin)
    pxmax, pymax = pproj(xmax, ymax)
    pwidth = pxmax - pxmin
    pheight = pymax - pymin

    bounds = (xmin, xmax, ymin, ymax)

    # Map aspect
    aspect = pwidth/pheight
    # This all seems unnecessary
    # fig_aspect = 1.0/(0.19 + 0.8/aspect)
    # figheight = FIGWIDTH / fig_aspect
    # figsize = (FIGWIDTH, figheight)
    # Make the figsize a constant, other functions will fit the map and
    # legends within the available space
    figsize = (FIGWIDTH, FIGHEIGHT)
    return (bounds, figsize, aspect)
Ejemplo n.º 22
0
def plotter(x, lat, lon, u, v, cmap, clevs, bati, lat_i, lat_f, lon_i, lon_f, cbar_label):
    import cartopy.crs as ccrs
    from cartopy.feature import NaturalEarthFeature
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import matplotlib.gridspec as gridspec
    import shapely.geometry as sgeom
    import numpy as np
    import xarray

    x_o, y_o = np.meshgrid(u.longitude, v.latitude)
    x1, y1 = np.meshgrid(lon, lat)
    x_b, y_b = np.meshgrid(bati['x'], bati['y'])

    fig = plt.figure(figsize=(10,12))
    ax = fig.add_subplot(111, projection=ccrs.Mercator())

    ax.set_extent([lon_i, lon_f, lat_f, lat_i], crs=ccrs.PlateCarree())
    tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white')
    ax.add_feature(tierra)
    ax.coastlines(resolution='50m')
    gl = ax.gridlines(crs=ccrs.PlateCarree(central_longitude=0),
                      draw_labels=True, color='white', linestyle='--', linewidth=.3)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    l1 = sgeom.LineString([(-51.67,-34.33), (-45, -34.33)])
    l2 = sgeom.LineString([(-52,-35), (-47.66, -31)])
    ax.add_geometries([l1,l2], ccrs.PlateCarree(), facecolor='none',
                      edgecolor='orange', linewidth=2)

    clr = ax.contourf(x1, y1, np.sqrt(u**2+v**2)*100, clevs,
                      transform=ccrs.PlateCarree(), cmap=cmap, extend='both')
    cbloc = ax.contour(x1, y1, np.sqrt(u**2+v**2), levels = 0.1, transform=ccrs.PlateCarree(),
                       linestyles='--', colors='k', linewidths=1.2)
    b = ax.contour(x_b, y_b, bati['z'].values, levels=[-1000,-200], colors='k', linewidths=1.3,
                    transform=ccrs.PlateCarree())
    cbar = fig.colorbar(clr, ax=ax, shrink=.7)
    cbar.ax.set_ylabel('m/s')

    return fig, ax
Ejemplo n.º 23
0
    def add_level1(self, myrecord, addThumbnail=False, addFeature=False):
        """ Add a level 1 dataset """
        print("Adding records to Level 1 core...")
        mylist = list()
        # print(myrecord)
        # print(json.dumps(myrecord, indent=4))
        mylist.append(myrecord)
        # print(mylist)
        try:
            self.solr1.add(mylist)
        except Exception as e:
            print("Something failed in SolR add", str(e))
        print("Level 1 record successfully added.")

        # print(mylist[0]['mmd_data_access_resource'])
        if addThumbnail:
            print("Checking tumbnails...")
            darlist = self.darextract(mylist[0]['mmd_data_access_resource'])
            print(darlist)
            print(type(darlist))
            try:
                if 'OGC WMS' in darlist:
                    getCapUrl = darlist['OGC WMS']
                    wms_layer = 'ice_concentration'  # NOTE: need to parse/read the  mmd_data_access_wms_layers_wms_layer
                    # myprojection = ccrs.NorthPolarStereo(central_longitude=10.0,true_scale_latitude=60.0)
                    myprojection = ccrs.Mercator()
                    myprojection = ccrs.PlateCarree()
                    self.add_thumbnail(url=darlist['OGC WMS'],
                                       layer=wms_layer, projection=myprojection)
                elif 'OPeNDAP' in darlist:
                    # To be added
                    print('')
            except Exception as e:
                print("Something failed in adding thumbnail, " + str(e))
                raise Warning("Couldn't add thumbnail.")
        elif addFeature:
            try:
                self.set_feature_type(mylist)
            except Exception as e:
                print("Something failed in adding feature type, " + str(e))
Ejemplo n.º 24
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(),
    ]

    fig = plt.figure(figsize=(10, 10))
    for i, prj in enumerate(projections, 1):
        ax = fig.add_subplot(5, 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())
Ejemplo n.º 25
0
def plotter(x, lat, lon, u, v, lat1, lon1, cmap, clevs, bati, lat_i, lat_f, lon_i, lon_f, cbar_label, title, kk):

    x_o, y_o = np.meshgrid(lon1, lat1)
    x1, y1 = np.meshgrid(lon, lat)
    x_b, y_b = np.meshgrid(bati['x'], bati['y'])

    fig = plt.figure(figsize=(10,12))
    ax = fig.add_subplot(111, projection=ccrs.Mercator())

    ax.set_extent([lon_i, lon_f, lat_f, lat_i], crs=ccrs.PlateCarree())
    tierra = NaturalEarthFeature('physical', 'land', '50m', edgecolor='black', facecolor='white')
    ax.add_feature(tierra)
    ax.coastlines(resolution='50m')
    gl = ax.gridlines(crs=ccrs.PlateCarree(central_longitude=0),
                      draw_labels=True, color='white', linestyle='--', linewidth=.3)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 15, 'rotation': 45}
    gl.ylabel_style = {'size': 15}
    box = sgeom.box(minx=-51.67, maxx=-50.33, miny=-34.33, maxy=-34.33)
    ax.add_geometries([box], ccrs.PlateCarree(), facecolor='none', linewidth=2.5,
                      edgecolor='black')

    clr = ax.contourf(x1, y1, x, clevs,
                      transform=ccrs.PlateCarree(), cmap=cmap, extend='both')
    b = ax.contour(x_b, y_b, bati['z'].values, levels=[-1000,-200], colors='k', linewidths=2,
                   linestyles='-', transform=ccrs.PlateCarree())
    qvr = ax.quiver(x_o, y_o, u, v,
                    units='xy', scale=0.4/111139, transform=ccrs.PlateCarree())

    cbar = fig.colorbar(clr, ax=ax, shrink=.7)
    cbar.ax.tick_params(labelsize=15)
    cbar.ax.set_ylabel(cbar_label, size=18)
    ax.quiverkey(qvr, .1, 1.1, .4, '40 cm/s', labelpos='E', fontproperties={'size': 18})
    ax.text(0.08, .93, kk, transform=ax.transAxes, size=22)
    plt.title(title)

    return fig, ax
Ejemplo n.º 26
0
def plotterchico(lat, lon, X, cmap, clevs, title, units):
    x, y = np.meshgrid(lon, lat)
    fig = plt.figure(figsize=(9, 7))
    ax = fig.add_subplot(111, projection=ccrs.Mercator())

    ax.set_extent([-80, -40, -56, -20], crs=ccrs.PlateCarree())
    tierra = NaturalEarthFeature('physical',
                                 'land',
                                 '50m',
                                 edgecolor='black',
                                 facecolor='white')
    ax.add_feature(tierra)
    ax.coastlines(resolution='50m')

    grid_style = dict(color='white', linestyle='--', linewidth=.3)
    gl = ax.gridlines(draw_labels=True, **grid_style)
    gl.xlabels_top = gl.ylabels_right = False
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER

    pc = ax.contourf(x,
                     y,
                     X,
                     clevs,
                     cmap=cmap,
                     extend='both',
                     transform=ccrs.PlateCarree())
    b = ax.contour(x_b,
                   y_b,
                   bati['z'].values,
                   levels=[-1000, -200],
                   colors='k',
                   linewidths=1.3,
                   linestyles='-',
                   transform=ccrs.PlateCarree())
    cbar = fig.colorbar(pc, ax=ax, shrink=0.9)
    cbar.ax.set_ylabel(units)
    ax.set_title(title)
    return fig, ax
def main():
    # to get the effect of having just the states without a map "background"
    # turn off the background patch and axes frame

    # Set projection and plot the main figure
    proj = ccrs.Mercator(central_longitude=115.,
                         min_latitude=-80.0,
                         max_latitude=84.0,
                         globe=None,
                         latitude_true_scale=21.0,
                         false_easting=0.0,
                         false_northing=0.0,
                         scale_factor=None)
    fig = plt.figure(figsize=[10, 8], frameon=True)

    ax = fig.add_axes([0.08, 0.05, 0.8, 0.94], projection=proj)

    # Set figure extent
    ax.set_extent([104, 118, 16, 27], crs=ccrs.PlateCarree())
    province_shp = shpreader.Reader(
        '../../UTILITY-2016/shp/cnmap/cnhimap.dbf').geometries()
    county_shp = shpreader.Reader(
        '../../UTILITY-2016/shp/cnmap/county_2004.dbf').geometries()
    ax.add_geometries(county_shp,
                      ccrs.PlateCarree(),
                      facecolor='none',
                      edgecolor='gray',
                      linewidth=0.5,
                      zorder=-1)
    ax.add_geometries(province_shp,
                      ccrs.PlateCarree(),
                      facecolor='none',
                      edgecolor='black',
                      linewidth=1.,
                      zorder=0)
    #    ax.add_geometries(province_shp, proj,facecolor='none', edgecolor='black',linewidth=1., zorder = 0)

    plt.savefig("../fig/test2.png", dpi=200, bbox_inches='tight')
Ejemplo n.º 28
0
def test_grid_labels_tight():
    # Ensure tight layout accounts for gridlines
    fig = plt.figure(figsize=(7, 5))

    crs_pc = ccrs.PlateCarree()
    crs_merc = ccrs.Mercator()

    ax = fig.add_subplot(2, 2, 1, projection=crs_pc)
    ax.coastlines(resolution="110m")
    ax.gridlines(draw_labels=True)

    ax = fig.add_subplot(2, 2, 2, projection=crs_merc)
    ax.coastlines(resolution="110m")
    ax.gridlines(draw_labels=True)

    # Matplotlib tight layout is also incorrect if cartopy fails
    # to adjust aspect ratios first. Relevant when aspect ratio has
    # changed due to set_extent.
    ax = fig.add_subplot(2, 2, 3, projection=crs_pc)
    ax.set_extent([-20, 10.0, 45.0, 70.0])
    ax.coastlines(resolution="110m")
    ax.gridlines(draw_labels=True)

    ax = fig.add_subplot(2, 2, 4, projection=crs_merc)
    ax.set_extent([-20, 10.0, 45.0, 70.0], crs=crs_pc)
    ax.coastlines(resolution="110m")
    gl = ax.gridlines(draw_labels=True)
    gl.rotate_labels = False

    # Apply tight layout
    fig.tight_layout()

    # Ensure gridliners were drawn
    for ax in fig.axes:
        for gl in ax._gridliners:
            assert hasattr(gl, '_drawn') and gl._drawn

    return fig
Ejemplo n.º 29
0
def plot_merc(s):
    proj = ccrs.Mercator()
    ax = plt.axes(projection=proj)
    ax.set_extent((s.bounds[0], s.bounds[2], s.bounds[1], s.bounds[3]),
                  crs=ccrs.PlateCarree())
    shape_feature = ShapelyFeature([s],
                                   ccrs.PlateCarree(),
                                   facecolor='#AAFFAA',
                                   edgecolor='k')
    ax.add_feature(shape_feature)

    gl = ax.gridlines(crs=ccrs.PlateCarree(),
                      draw_labels=True,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--')
    gl.xlabels_top = False
    gl.ylabels_left = False
    gl.xlabel_style = {'size': 10, 'color': 'black'}
    gl.ylabel_style = {'size': 10, 'color': 'black'}

    return gl
Ejemplo n.º 30
0
def get_transformation(crs_in):
    """ Get projection and its units to use in cartopy transforamtions from
    current crs

    Returns:
        ccrs.Projection, str
    """
    try:
        if CRS.from_user_input(crs_in) == CRS.from_user_input({'init':'epsg:3395'}):
            crs_epsg = ccrs.Mercator()
        else:
            crs_epsg = ccrs.epsg(CRS.from_user_input(crs_in).to_epsg())
    except ValueError:
        crs_epsg = ccrs.PlateCarree()
    except requests.exceptions.ConnectionError:
        LOGGER.warning('No internet connection. Using projection PlateCarree in plot.')
        crs_epsg = ccrs.PlateCarree()

    try:
        units = crs_epsg.proj4_params['units']
    except KeyError:
        units = '°'
    return crs_epsg, units