How to use the cartopy.io.shapereader.Reader 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 raybellwaves / cfanalytics / cfanalytics / core / cfplot.py View on Github external
Parameters
        ----------
        _f : str
            Natural Earth file name
        attname : str
            Expected attribute name
            
        Returns
        -------
        self.geoms : list of geometries
        """
        filename = shapereader.natural_earth(resolution='10m',
                                             category='cultural',
                                             name=_f)
        reader = shapereader.Reader(filename)
        records = list(reader.records())
        for _loc in records:
            if _loc.attributes[attname] in self.loc_names:
                if _loc.attributes[attname] == 'France':
                    # Only want mainland France. Not its territories
                    try:
                        self.geoms += _loc.geometry[-1]
                    except TypeError:
                        self.geoms.append(_loc.geometry[-1])
                else:
                    try:
                        self.geoms += _loc.geometry
                    except TypeError:
                        self.geoms.append(_loc.geometry)                    
        return self
github DTMilodowski / LiDAR_canopy / src / canopy_structure_plots.py View on Github external
country_shp = '/home/dmilodow/DataStore_DTM/EOlaboratory/Areas/NaturalEarth/10m_cultural/ne_10m_admin_0_boundary_lines_land.shp'
    shp = Reader(country_shp)
    Boundaries_left = [i for i in shp.records()
                    if i.attributes['adm0_left']=='Malaysia']
    Boundaries_right = [i for i in shp.records()
                    if i.attributes['adm0_right']=='Malaysia']
    for b1 in Boundaries_right:
        if b1.attributes['adm0_left'] != 'Singapore':
            sp = ShapelyFeature(b1.geometry, crs,  facecolor = 'none', edgecolor='black')
            ax.add_feature(sp)
    for b2 in Boundaries_left:
        sp = ShapelyFeature(b2.geometry, crs,  facecolor = 'none', edgecolor='black')
        ax.add_feature(sp)

    states_shp = '/home/dmilodow/DataStore_DTM/EOlaboratory/Areas/NaturalEarth/10m_cultural/ne_10m_admin_1_states_provinces_lines_shp.shp'
    shp = Reader(states_shp)
    Boundaries = [i for i in shp.records()
                    if i.attributes['adm0_name']=='Malaysia']
    for b in Boundaries:
        ax.plot(b.geometry.coords.xy[0],b.geometry.coords.xy[1], ":", color='0.1',lw=1)

    # Plot locations
    plot_shp = 'plot_locations_for_location_map_WGS84.shp'
    pshp = Reader(plot_shp)
    for pp in pshp.records():
        col=colour[1]
        if pp.attributes['ForestType'] == 'OG':
            col = colour[0]
        elif pp.attributes['ForestType'] == 'ML':
            col=colour[2]
        ax.plot(pp.geometry.coords.xy[0],pp.geometry.coords.xy[1], marker='o', mfc=col,mec='white', mew=0.5, markersize=6)
github Nukesor / gitalizer / gitalizer / plot / plotting / contributor_travel_path.py View on Github external
self.countries = list(shpreader.Reader(countries_shp).records())
        self.countries_by_name = {}
        self.countries_by_iso_a2 = {}
        for country in shpreader.Reader(countries_shp).records():
            self.countries_by_name[country.attributes['NAME_LONG']] = country
            self.countries_by_iso_a2[country.attributes['ISO_A2']] = country

        # Get all states and create a dictionary by name
        states_provinces_shp = shpreader.natural_earth(
            resolution='50m',
            category='cultural',
            name='admin_1_states_provinces',
        )
#        full_list = list(shpreader.Reader(states_provinces_shp).records())
#        self.states = [x for x in full_list if x.attributes['type_en'] == 'State']
        self.states = list(shpreader.Reader(states_provinces_shp).records())
        self.states_by_name = {}
        for state in self.states:
            self.states_by_name[state.attributes['name']] = state

        # Get all timezones and create a dictionary by name
        timezones_shp = shpreader.natural_earth(
            resolution='10m',
            category='cultural',
            name='time_zones',
        )
        self.timezones = list(shpreader.Reader(timezones_shp).records())
        self.timezones_by_name = {}
        for timezone in shpreader.Reader(timezones_shp).records():
            # Try to get the actual name. Something like `Europe/Berlin`
            timezone_name = timezone.attributes['tz_name1st']
            # If there is no name, we default to the utc offset name `-5` `+4.5`
github Unidata / MetPy / src / metpy / plots / cartopy_utils.py View on Github external
def geometries(self):
        """Return an iterator of (shapely) geometries for this feature."""
        import cartopy.io.shapereader as shapereader
        # Ensure that the associated files are in the cache
        fname = '{}_{}'.format(self.name, self.scale)
        for extension in ['.dbf', '.shx']:
            get_test_data(fname + extension)
        path = get_test_data(fname + '.shp', as_file_obj=False)
        return iter(tuple(shapereader.Reader(path).geometries()))
github SuperElastix / SimpleElastix / Utilities / Statistics / download_stats.py View on Github external
norm = mpl.colors.LogNorm(vmin=min_dl, vmax=max_dl)
total_users = c_series.sum()
shapename = 'admin_0_countries'
countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename)

plt.figure(figsize=(14,8))
ax = plt.axes(projection=ccrs.Robinson() )
ax.add_feature(cf.BORDERS)
ax.add_feature(cf.COASTLINE)
#ax.add_feature(cf.OCEAN)
#ax.add_feature(cf.LAND)

hdl_dict = dict()

for country in shpreader.Reader(countries_shp).records():
    name = country.attributes['name_long']
    if name in c_series:
        num_users = c_series[name]
        hdl = ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                               facecolor=cmap(norm(num_users),alpha=True))
        hdl_dict[name] = hdl

# Add ColorBar
sm = plt.cm.ScalarMappable(cmap=cmap,norm=norm)
sm._A = [] # WHAT? DANGER
plt.colorbar(sm,ax=ax)
plt.title("Source Forge Downloads by Country\n{0} to {1}".format(start_date, end_date))

# Add Legend
cnt = (cbo_df.sum(axis=1).sort_values(ascending=False).cumsum()/total < percent).sum()
github Nukesor / gitalizer / gitalizer / plot / plotting / contributor_travel_path.py View on Github external
#        full_list = list(shpreader.Reader(states_provinces_shp).records())
#        self.states = [x for x in full_list if x.attributes['type_en'] == 'State']
        self.states = list(shpreader.Reader(states_provinces_shp).records())
        self.states_by_name = {}
        for state in self.states:
            self.states_by_name[state.attributes['name']] = state

        # Get all timezones and create a dictionary by name
        timezones_shp = shpreader.natural_earth(
            resolution='10m',
            category='cultural',
            name='time_zones',
        )
        self.timezones = list(shpreader.Reader(timezones_shp).records())
        self.timezones_by_name = {}
        for timezone in shpreader.Reader(timezones_shp).records():
            # Try to get the actual name. Something like `Europe/Berlin`
            timezone_name = timezone.attributes['tz_name1st']
            # If there is no name, we default to the utc offset name `-5` `+4.5`
            if timezone_name == '':
                timezone_name = timezone.attributes['name']

            if timezone_name not in self.timezones_by_name.keys():
                self.timezones_by_name[timezone_name] = timezone
github YvZheng / pycwr / pycwr / configure / location_config.py View on Github external
# -*- coding: utf-8 -*-
import cartopy.io.shapereader as shpreader
import pandas as pd
import os

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Radar_info_Path = os.path.join(ROOT_DIR, "data", "radar_info.json")
CN_shp_path = os.path.join(ROOT_DIR, "data", "CHN_pronvices.shp")
last_open_dir = os.path.join(ROOT_DIR, "data", "default_opendir.json")
mbf_path = os.path.join(ROOT_DIR, "data", "beta_function_parameters.nc")

radar_info = pd.read_json(Radar_info_Path)
CN_shp_info = shpreader.Reader(CN_shp_path)
github jvkersch / pyconcorde / examples / us_state_capitals.py View on Github external
import cartopy.io.shapereader as shpreader

ax = plt.axes([0, 0, 1, 1], projection=ccrs.LambertConformal())
ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())

shapename = 'admin_1_states_provinces_lakes_shp'
states_shp = shpreader.natural_earth(resolution='110m',
                                     category='cultural', name=shapename)

ax.background_patch.set_visible(False)
ax.outline_patch.set_visible(False)

tour = sgeom.LineString(list(zip(solution.lon, solution.lat)))
capitals = sgeom.MultiPoint(list(zip(solution.lon, solution.lat)))

for state in shpreader.Reader(states_shp).geometries():
    facecolor = [0.9375, 0.9375, 0.859375]
    edgecolor = 'black'

    ax.add_geometries([state], ccrs.PlateCarree(),
                      facecolor=facecolor, edgecolor=edgecolor)

ax.add_geometries([tour], ccrs.PlateCarree(),
                  facecolor='none', edgecolor='red')
for lat, lon in zip(solution.lat, solution.lon):
    ax.plot(lon, lat, 'ro', transform=ccrs.PlateCarree())
    
plt.savefig("us_state_capitals.png", bbox_inches='tight')
plt.show()
github ARM-DOE / pyart / pyart / graph / radarmapdisplay.py View on Github external
lambert_yticks(ax, lat_lines)
            else:
                ax.gridlines(xlocs=lon_lines, ylocs=lat_lines)

        # plot the data and optionally the shape file
        # we need to convert the radar gate locations (x and y) which are in
        # km to meters we also need to give the original projection of the
        # data which is stored in self.grid_projection

        if shapefile is not None:
            from cartopy.io.shapereader import Reader
            if shapefile_kwargs is None:
                shapefile_kwargs = {}
            if 'crs' not in shapefile_kwargs:
                shapefile_kwargs['crs'] = cartopy.crs.PlateCarree()
            ax.add_geometries(Reader(shapefile).geometries(),
                              **shapefile_kwargs)

        if title_flag:
            self._set_title(field, sweep, title, ax)

        # add plot and field to lists
        self.plots.append(pm)
        self.plot_vars.append(field)

        if colorbar_flag:
            self.plot_colorbar(
                mappable=pm, label=colorbar_label, field=field, fig=fig,
                ax=ax, ticks=ticks, ticklabs=ticklabs)
        # keep track of this GeoAxes object for later
        self.ax = ax
        return