Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _get_country_shape(country):
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
area = world[world.name == country]
assert len(area) == 1
area = area.to_crs(epsg=3395) # convert to World Mercator CRS
return area.iloc[0].geometry # get the Polygon
def test_spatial_join(self):
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
countries = world[['geometry', 'name']]
countries = countries.rename(columns={'name':'country'})
cities_with_country = geopandas.sjoin(cities, countries, how="inner", op='intersects')
self.assertTrue(cities_with_country.size > 1)
def test_calculate_polygon_areas_world():
import geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world = world[world.continent != 'Antarctica'].to_crs(epsg=3395) # meters as unit!
areas = calculate_polygon_areas(world.geometry)
assert len(areas) == len(world)
assert all(0 <= a < 9e13 for a in areas)
areas_km2 = calculate_polygon_areas(world.geometry, m2_to_km2=True)
assert len(areas_km2) == len(world)
assert all(isclose(a_m, a_km * 1e6) for a_m, a_km in zip(areas, areas_km2))
###############################################################################
import geopandas as gpd
import matplotlib.pyplot as plt
world = gpd.read_file('/gdata/GSHHS_c.shp')
world['gdp_per_cap'] = world.area
world.plot(column='gdp_per_cap')
plt.show()
###############################################################################
world.plot(column='gdp_per_cap', cmap='OrRd');
plt.show()
###############################################################################
world.plot(column='gdp_per_cap', cmap='OrRd',
scheme='quantiles')
plt.show()
###############################################################################
cities = gpd.read_file(gpd.datasets.get_path(
'naturalearth_cities'))
cities.plot(marker='*', color='green', markersize=5)
###############################################################################
cities = cities.to_crs(world.crs)
###############################################################################
base = world.plot(color='white')
cities.plot(ax=base, marker='o',color='red',markersize=5)
plt.show()
self.project_dir = os.path.abspath(project_dir)
self.start = start
self.end = end
self.data_mount = data_mount
self.download_dir = download_dir
self.inventory_dir = inventory_dir
self.processing_dir = processing_dir
self.temp_dir = temp_dir
# handle the import of different aoi formats and transform
# to a WKT string
if aoi.split('.')[-1] != 'shp' and len(aoi) == 3:
# get lowres data
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
country = world.name[world.iso_a3 == aoi].values[0]
print(' INFO: Getting the country boundaries from Geopandas low'
' resolution data for {}'.format(country))
self.aoi = (world['geometry']
[world['iso_a3'] == aoi].values[0].to_wkt())
elif aoi.split('.')[-1] == 'shp':
self.aoi = str(vec.shp_to_wkt(aoi))
print(' INFO: Using {} shapefile as Area of Interest definition.')
else:
try:
loads(str(aoi))
except:
print(' ERROR: No valid OST AOI defintion.')
sys.exit()
else:
def find_locations(people):
alpha_3_to_2 = {c.alpha_3: c.alpha_2 for c in pycountry.countries}
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
locations = set()
for p in people:
if p['locations']:
locations.add(p['locations'][0])
q = ["'%s'" % l.replace("'", "''") for l in locations if l]
q = '(%s)' % ','.join(q)
cursor.execute(
"select wikipedia.title, ST_AsText(wikipedia.lng_lat) from wikipedia where title in " + q)
loc_by_lat_lng = {
t: None if p is None else wkt.loads(p)
for t, p in cursor.fetchall()
}
locs_with_coos = [k for k in loc_by_lat_lng if loc_by_lat_lng[k]]
coos_for_loc = [loc_by_lat_lng[k] for k in locs_with_coos]
loc_df = gpd.GeoDataFrame([{'location': k} for k in locs_with_coos],
from geovoronoi import coords_to_points, points_to_coords, voronoi_regions_from_coords, calculate_polygon_areas
from geovoronoi.plotting import subplot_for_map, plot_voronoi_polys_with_points_in_area
logging.basicConfig(level=logging.INFO)
geovoronoi_log = logging.getLogger('geovoronoi')
geovoronoi_log.setLevel(logging.INFO)
geovoronoi_log.propagate = True
N_POINTS = 20
COUNTRY = 'Spain'
np.random.seed(123)
print('loading country `%s` from naturalearth_lowres' % COUNTRY)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
area = world[world.name == COUNTRY]
assert len(area) == 1
print('CRS:', area.crs) # gives epsg:4326 -> WGS 84
area = area.to_crs(epsg=3395) # convert to World Mercator CRS
area_shape = area.iloc[0].geometry # get the Polygon
# generate some random points within the bounds
minx, miny, maxx, maxy = area_shape.bounds
randx = np.random.uniform(minx, maxx, N_POINTS)
randy = np.random.uniform(miny, maxy, N_POINTS)
coords = np.vstack((randx, randy)).T
# use only the points inside the geographic area
--------------------------------
This example shows how you can add a background basemap to plots created
with the geopandas ``.plot()`` method. This makes use of the
`contextily `__ package to retrieve
web map tiles from several sources (OpenStreetMap, Stamen).
"""
# sphinx_gallery_thumbnail_number = 3
import geopandas
###############################################################################
# Let's use the NYC borough boundary data that is available in geopandas
# datasets. Plotting this gives the following result:
df = geopandas.read_file(geopandas.datasets.get_path('nybb'))
ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')
###############################################################################
# Convert the data to Web Mercator
# ================================
#
# Web map tiles are typically provided in
# `Web Mercator `__
# (`EPSG 3857 `__), so we need to make sure to convert
# our data first to the same CRS to combine our polygons and background tiles
# in the same map:
df = df.to_crs(epsg=3857)
###############################################################################
# Contextily helper function
from geovoronoi.plotting import subplot_for_map, plot_voronoi_polys_with_points_in_area
logging.basicConfig(level=logging.INFO)
geovoronoi_log = logging.getLogger('geovoronoi')
geovoronoi_log.setLevel(logging.INFO)
geovoronoi_log.propagate = True
N_POINTS = 20
N_DUPL = 10
COUNTRY = 'Sweden'
np.random.seed(123)
print('loading country `%s` from naturalearth_lowres' % COUNTRY)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
area = world[world.name == COUNTRY]
assert len(area) == 1
print('CRS:', area.crs) # gives epsg:4326 -> WGS 84
area = area.to_crs(epsg=3395) # convert to World Mercator CRS
area_shape = area.iloc[0].geometry # get the Polygon
# generate some random points within the bounds
minx, miny, maxx, maxy = area_shape.bounds
randx = np.random.uniform(minx, maxx, N_POINTS)
randy = np.random.uniform(miny, maxy, N_POINTS)
coords = np.vstack((randx, randy)).T
# use only the points inside the geographic area
def plot_inventory(aoi, inventory_df, transparency=0.05):
import matplotlib.pyplot as plt
# load world borders for background
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# import aoi as gdf
aoi_gdf = wkt_to_gdf(aoi)
# get bounds of AOI
bounds = inventory_df.geometry.bounds
# get world map as base
base = world.plot(color='lightgrey', edgecolor='white')
# plot aoi
aoi_gdf.plot(ax=base, color='None', edgecolor='black')
# plot footprints
inventory_df.plot(ax=base, alpha=transparency)