How to use the cartopy.crs function in Cartopy

To help you get started, we’ve selected a few Cartopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github holoviz / hvplot / hvplot / converter.py View on Github external
try:
                import geoviews # noqa
            except ImportError:
                raise ImportError('In order to use geo-related features '
                                  'the geoviews library must be available. '
                                  'It can be installed with:\n  conda '
                                  'install -c pyviz geoviews')
        if self.geo:
            if self.kind not in self._geo_types:
                param.main.warning(
                    "geo option cannot be used with kind=%r plot "
                    "type. Geographic plots are only supported for "
                    "following plot types: %r" % (self.kind, self._geo_types))
            from cartopy import crs as ccrs
            from geoviews.util import project_extents
            proj_crs = projection or ccrs.GOOGLE_MERCATOR
            if self.crs != proj_crs:
                px0, py0, px1, py1 = ccrs.GOOGLE_MERCATOR.boundary.bounds
                x0, x1 = xlim or (px0, px1)
                y0, y1 = ylim or (py0, py1)
                extents = (x0, y0, x1, y1)
                x0, y0, x1, y1 = project_extents(extents, self.crs, proj_crs)
                if xlim:
                    xlim = (x0, x1)
                if ylim:
                    ylim = (y0, y1)

        # Operations
        self.datashade = datashade
        self.rasterize = rasterize
        self.dynspread = dynspread
        self.aggregator = aggregator
github CyanideCN / PyCINRAD / cinrad / visualize / ppi.py View on Github external
def _plot(self, **kwargs):
        from cinrad.visualize.utils import plot_kw

        dtype = self.data.dtype
        lon, lat, var = _prepare(self.data, dtype)
        if (
            self.settings["extent"] == None
        ):  # 增加判断,城市名称绘制在选择区域内,否则自动绘制在data.lon和data.lat范围内
            self.settings["extent"] = [lon.min(), lon.max(), lat.min(), lat.max()]
        # When plot single radar, azimuthal equidistant projection is used.
        # The data which has code like 'Z9XXX' is considered as single radar.
        code = self.data.code
        if isinstance(self.data, Radial) or (
            code.startswith("Z") and code[1:].isnumeric()
        ):
            proj = ccrs.AzimuthalEquidistant(
                central_longitude=self.data.stp["lon"],
                central_latitude=self.data.stp["lat"],
            )
        else:
            proj = ccrs.PlateCarree()
        self.geoax: GeoAxes = set_geoaxes(
            self.fig, proj, extent=self.settings["extent"]
        )
        if self.data.dtype in ["VEL", "SW"] and self.data.include_rf:
            rf = var[1]
            var = var[0]
        pnorm, cnorm, clabel = self._norm()
        pcmap, ccmap = self._cmap()
        self.geoax.pcolormesh(
            lon, lat, var, norm=pnorm, cmap=pcmap, transform=self.data_crs, **kwargs
        )
github climate-processes / tobac / tobac / plotting.py View on Github external
def plot_tracks_mask_field_loop(track,field,mask,features,axes=None,name=None,plot_dir='./',
                                figsize=(10./2.54,10./2.54),dpi=300,
                                margin_left=0.05,margin_right=0.05,margin_bottom=0.05,margin_top=0.05,
                                **kwargs):
    import cartopy.crs as ccrs
    import os
    from iris import Constraint
    os.makedirs(plot_dir,exist_ok=True)
    time=mask.coord('time')
    if name is None:
        name=field.name()
    for time_i in time.points:
        datetime_i=time.units.num2date(time_i)
        constraint_time = Constraint(time=datetime_i)
        fig1,ax1=plt.subplots(ncols=1, nrows=1,figsize=figsize, subplot_kw={'projection': ccrs.PlateCarree()})
        datestring_file=datetime_i.strftime('%Y-%m-%d_%H:%M:%S')
        field_i=field.extract(constraint_time)
        mask_i=mask.extract(constraint_time)
        track_i=track[track['time']==datetime_i]
        features_i=features[features['time']==datetime_i]
        ax1=plot_tracks_mask_field(track=track_i,field=field_i,mask=mask_i,features=features_i,
                                   axes=ax1,**kwargs)
        fig1.subplots_adjust(left=margin_left, bottom=margin_bottom, right=1-margin_right, top=1-margin_top)
        os.makedirs(plot_dir, exist_ok=True)
        savepath_png=os.path.join(plot_dir,name+'_'+datestring_file+'.png')
        fig1.savefig(savepath_png,dpi=dpi)
        logging.debug('Figure plotted to ' + str(savepath_png))

        plt.close()
github jimmy60504 / SeisNN / scripts / prototypes / plot_HL_map.py View on Github external
import os
import numpy as np
import matplotlib.pyplot as plt

import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter

from seisnn.io import read_hyp, read_event_list
from seisnn.utils import get_config

W, E, S, N = 121.2, 121.9, 23.5, 24.3
stamen_terrain = cimgt.Stamen('terrain-background')
fig = plt.figure(figsize=(8, 11))
ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs)
ax.set_extent([W, E, S, N], crs=ccrs.PlateCarree())
ax.add_image(stamen_terrain, 11)

events = read_event_list('HL2017')
HL_eq = []
for event in events:
    HL_eq.append([event.origins[0].longitude, event.origins[0].latitude])
HL_eq = np.array(HL_eq).T
ax.scatter(HL_eq[0], HL_eq[1], label='Event',
           transform=ccrs.PlateCarree(), color='#555555', edgecolors='k', linewidth=0.3, marker='o', s=10)

geom = read_hyp('HL2017.HYP')
HL_station = []
for k, station in geom.items():
    HL_station.append([station['longitude'], station['latitude'], ])
HL_station = np.array(HL_station).T
ax.scatter(HL_station[0], HL_station[1], label='HL 2017 station',
github akrherz / pyIEM / src / pyiem / reference.py View on Github external
Z_FILL,
    Z_FILL_LABEL,
    Z_POLITICAL,
    Z_CLIP,
    Z_CLIP2,
    Z_OVERLAY,
    Z_OVERLAY_LABEL,
    Z_OVERLAY2,
    Z_OVERLAY2_LABEL,
] = range(1, 11)

TRACE_VALUE = 0.0001
TWEET_CHARS = 280

EPSG = {
    5070: ccrs.AlbersEqualArea(
        central_longitude=-96,
        central_latitude=23,
        standard_parallels=[29.5, 45.5],
    ),
    2163: ccrs.LambertAzimuthalEqualArea(
        central_latitude=45, central_longitude=-100
    ),
}

IA_WEST = -96.7
IA_EAST = -90.1
IA_NORTH = 43.61
IA_SOUTH = 40.37

MW_WEST = -104.2
MW_EAST = -80.1
github fatiando / rockhound / examples / sample_data / baja_bathymetry.py View on Github external
"""
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import rockhound as rh


# The data are in a pandas.DataFrame
data = rh.fetch_baja_bathymetry()
print(data.head())

# Make a Mercator map of the data using Cartopy
plt.figure(figsize=(7, 6))
ax = plt.axes(projection=ccrs.Mercator())
ax.set_title("Bathymetry from Baja California")
# Plot the bathymetry as colored circles. Cartopy requires setting the
# projection of the original data through the transform argument.
# Use PlateCarree for geographic data.
plt.scatter(
    data.longitude,
    data.latitude,
    c=data.bathymetry_m,
    s=0.1,
    transform=ccrs.PlateCarree(),
)
plt.colorbar().set_label("meters")

# Add tick labels and land and ocean features to the map.
crs = ccrs.PlateCarree()
region = (245.0, 254.705, 20.0, 29.99)
github SciTools / cartopy / lib / cartopy / mpl / geoaxes.py View on Github external
# Determine target projection based on requested CRS.
        if crs is None:
            proj = self.projection
        elif isinstance(crs, ccrs.Projection):
            proj = crs
        else:
            # Attempt to select suitable projection for
            # non-projection CRS.
            if isinstance(crs, ccrs.RotatedGeodetic):
                proj = ccrs.RotatedPole(crs.proj4_params['lon_0'] - 180,
                                        crs.proj4_params['o_lat_p'])
                warnings.warn('Approximating coordinate system {!r} with a '
                              'RotatedPole projection.'.format(crs))
            elif hasattr(crs, 'is_geodetic') and crs.is_geodetic():
                proj = ccrs.PlateCarree(crs.globe)
                warnings.warn('Approximating coordinate system {!r} with the '
                              'PlateCarree projection.'.format(crs))
            else:
                raise ValueError('Cannot determine extent in'
                                 ' coordinate system {!r}'.format(crs))

        # Calculate intersection with boundary and project if necessary.
        boundary_poly = sgeom.Polygon(self.projection.boundary)
        if proj != self.projection:
            # Erode boundary by threshold to avoid transform issues.
            # This is a workaround for numerical issues at the boundary.
            eroded_boundary = boundary_poly.buffer(-self.projection.threshold)
            geom_in_src_proj = eroded_boundary.intersection(
                domain_in_src_proj)
            geom_in_crs = proj.project_geometry(geom_in_src_proj,
                                                self.projection)
github SciTools / iris / lib / iris / coord_systems.py View on Github external
def as_cartopy_crs(self):
        globe = self._ellipsoid_to_globe(self.ellipsoid, ccrs.Globe())

        return ccrs.Stereographic(
            self.central_lat,
            self.central_lon,
            self.false_easting,
            self.false_northing,
            self.true_scale_lat,
            globe=globe,
        )
github holoviz / hvplot / hvplot / converter.py View on Github external
except ImportError:
                raise ImportError('In order to use geo-related features '
                                  'the geoviews library must be available. '
                                  'It can be installed with:\n  conda '
                                  'install -c pyviz geoviews')
        if self.geo:
            if self.kind not in self._geo_types:
                param.main.warning(
                    "geo option cannot be used with kind=%r plot "
                    "type. Geographic plots are only supported for "
                    "following plot types: %r" % (self.kind, self._geo_types))
            from cartopy import crs as ccrs
            from geoviews.util import project_extents
            proj_crs = projection or ccrs.GOOGLE_MERCATOR
            if self.crs != proj_crs:
                px0, py0, px1, py1 = ccrs.GOOGLE_MERCATOR.boundary.bounds
                x0, x1 = xlim or (px0, px1)
                y0, y1 = ylim or (py0, py1)
                extents = (x0, y0, x1, y1)
                x0, y0, x1, y1 = project_extents(extents, self.crs, proj_crs)
                if xlim:
                    xlim = (x0, x1)
                if ylim:
                    ylim = (y0, y1)

        # Operations
        self.datashade = datashade
        self.rasterize = rasterize
        self.dynspread = dynspread
        self.aggregator = aggregator
        self.precompute = precompute
        self.x_sampling = x_sampling