blacken the rest of the code (docs, benchmarks) (#2636)

This commit is contained in:
Martin Fleischmann
2022-11-03 20:03:10 +01:00
committed by GitHub
parent b6174b4471
commit 5dc982edbf
21 changed files with 444 additions and 299 deletions
+76 -39
View File
@@ -10,86 +10,123 @@ def with_attributes(**attrs):
for key, value in attrs.items():
setattr(func, key, value)
return func
return decorator
class Bench:
def setup(self, *args):
self.points = GeoSeries([Point(i, i) for i in range(100000)])
triangles = GeoSeries([Polygon([(random.random(), random.random())
for _ in range(3)])
for _ in range(1000)])
triangles2 = triangles.copy().iloc[np.random.choice(1000, 1000)]
triangles3 = GeoSeries([Polygon([(random.random(), random.random())
for _ in range(3)])
for _ in range(10000)])
triangles4 = GeoSeries([
MultiPolygon([
triangles = GeoSeries(
[
Polygon([(random.random(), random.random()) for _ in range(3)])
]) for _ in range(10000)])
triangle = Polygon([(random.random(), random.random())
for _ in range(3)])
for _ in range(1000)
]
)
triangles2 = triangles.copy().iloc[np.random.choice(1000, 1000)]
triangles3 = GeoSeries(
[
Polygon([(random.random(), random.random()) for _ in range(3)])
for _ in range(10000)
]
)
triangles4 = GeoSeries(
[
MultiPolygon(
[Polygon([(random.random(), random.random()) for _ in range(3)])]
)
for _ in range(10000)
]
)
triangle = Polygon([(random.random(), random.random()) for _ in range(3)])
self.triangles, self.triangles2 = triangles, triangles2
self.triangles_big = triangles3
self.multi_triangles = triangles4
self.triangle = triangle
@with_attributes(param_names=['op'],
params=[('contains', 'crosses', 'disjoint', 'intersects',
'overlaps', 'touches', 'within', 'geom_equals',
'geom_almost_equals', 'geom_equals_exact')])
@with_attributes(
param_names=["op"],
params=[
(
"contains",
"crosses",
"disjoint",
"intersects",
"overlaps",
"touches",
"within",
"geom_equals",
"geom_almost_equals",
"geom_equals_exact",
)
],
)
def time_binary_predicate(self, op):
getattr(self.triangles, op)(self.triangle)
@with_attributes(param_names=['op'],
params=[('contains', 'crosses', 'disjoint', 'intersects',
'overlaps', 'touches', 'within', 'geom_equals',
'geom_almost_equals')]) # 'geom_equals_exact')])
@with_attributes(
param_names=["op"],
params=[
(
"contains",
"crosses",
"disjoint",
"intersects",
"overlaps",
"touches",
"within",
"geom_equals",
"geom_almost_equals",
)
],
) # 'geom_equals_exact')])
def time_binary_predicate_vector(self, op):
getattr(self.triangles, op)(self.triangles2)
@with_attributes(param_names=['op'],
params=[('distance')])
@with_attributes(param_names=["op"], params=[("distance")])
def time_binary_float(self, op):
getattr(self.triangles, op)(self.triangle)
@with_attributes(param_names=['op'],
params=[('distance')])
@with_attributes(param_names=["op"], params=[("distance")])
def time_binary_float_vector(self, op):
getattr(self.triangles, op)(self.triangles2)
@with_attributes(param_names=['op'],
params=[('difference', 'symmetric_difference', 'union',
'intersection')])
@with_attributes(
param_names=["op"],
params=[("difference", "symmetric_difference", "union", "intersection")],
)
def time_binary_geo(self, op):
getattr(self.triangles, op)(self.triangle)
@with_attributes(param_names=['op'],
params=[('difference', 'symmetric_difference', 'union',
'intersection')])
@with_attributes(
param_names=["op"],
params=[("difference", "symmetric_difference", "union", "intersection")],
)
def time_binary_geo_vector(self, op):
getattr(self.triangles, op)(self.triangles2)
@with_attributes(param_names=['op'],
params=[('is_valid', 'is_empty', 'is_simple', 'is_ring')])
@with_attributes(
param_names=["op"], params=[("is_valid", "is_empty", "is_simple", "is_ring")]
)
def time_unary_predicate(self, op):
getattr(self.triangles, op)
@with_attributes(param_names=['op'],
params=[('area', 'length')])
@with_attributes(param_names=["op"], params=[("area", "length")])
def time_unary_float(self, op):
getattr(self.triangles_big, op)
@with_attributes(param_names=['op'],
params=[('boundary', 'centroid', 'convex_hull',
'envelope', 'exterior', 'interiors')])
@with_attributes(
param_names=["op"],
params=[
("boundary", "centroid", "convex_hull", "envelope", "exterior", "interiors")
],
)
def time_unary_geo(self, op):
getattr(self.triangles, op)
def time_unary_geo_representative_point(self, *args):
getattr(self.triangles, 'representative_point')()
getattr(self.triangles, "representative_point")()
def time_geom_type(self, *args):
self.triangles_big.geom_type
+33 -24
View File
@@ -5,18 +5,18 @@ from shapely.geometry import Point, Polygon
class Countries:
param_names = ['how']
params = [('intersection', 'union', 'identity', 'symmetric_difference',
'difference')]
param_names = ["how"]
params = [
("intersection", "union", "identity", "symmetric_difference", "difference")
]
def setup(self, *args):
world = read_file(datasets.get_path('naturalearth_lowres'))
capitals = read_file(datasets.get_path('naturalearth_cities'))
countries = world[['geometry', 'name']]
countries = countries.to_crs('+init=epsg:3395')[
countries.name != "Antarctica"]
capitals = capitals.to_crs('+init=epsg:3395')
capitals['geometry'] = capitals.buffer(500000)
world = read_file(datasets.get_path("naturalearth_lowres"))
capitals = read_file(datasets.get_path("naturalearth_cities"))
countries = world[["geometry", "name"]]
countries = countries.to_crs("+init=epsg:3395")[countries.name != "Antarctica"]
capitals = capitals.to_crs("+init=epsg:3395")
capitals["geometry"] = capitals.buffer(500000)
self.countries = countries
self.capitals = capitals
@@ -27,18 +27,27 @@ class Countries:
class Small:
param_names = ['how']
params = [('intersection', 'union', 'identity', 'symmetric_difference',
'difference')]
param_names = ["how"]
params = [
("intersection", "union", "identity", "symmetric_difference", "difference")
]
def setup(self, *args):
polys1 = GeoSeries([Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),
Polygon([(2, 2), (4, 2), (4, 4), (2, 4)])])
polys2 = GeoSeries([Polygon([(1, 1), (3, 1), (3, 3), (1, 3)]),
Polygon([(3, 3), (5, 3), (5, 5), (3, 5)])])
polys1 = GeoSeries(
[
Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),
Polygon([(2, 2), (4, 2), (4, 4), (2, 4)]),
]
)
polys2 = GeoSeries(
[
Polygon([(1, 1), (3, 1), (3, 3), (1, 3)]),
Polygon([(3, 3), (5, 3), (5, 5), (3, 5)]),
]
)
df1 = GeoDataFrame({'geometry': polys1, 'df1': [1, 2]})
df2 = GeoDataFrame({'geometry': polys2, 'df2': [1, 2]})
df1 = GeoDataFrame({"geometry": polys1, "df1": [1, 2]})
df2 = GeoDataFrame({"geometry": polys2, "df2": [1, 2]})
self.df1, self.df2 = df1, df2
@@ -48,16 +57,16 @@ class Small:
class ManyPoints:
param_names = ['how']
params = [('intersection', 'union', 'identity', 'symmetric_difference',
'difference')]
param_names = ["how"]
params = [
("intersection", "union", "identity", "symmetric_difference", "difference")
]
def setup(self, *args):
points = GeoDataFrame(geometry=[Point(i, i) for i in range(1000)])
base = np.array([[0, 0], [0, 100], [100, 100], [100, 0]])
polys = GeoDataFrame(
geometry=[Polygon(base + i * 100) for i in range(10)])
polys = GeoDataFrame(geometry=[Polygon(base + i * 100) for i in range(10)])
self.df1, self.df2 = points, polys
+2 -7
View File
@@ -77,9 +77,7 @@ class BenchIndexCreation:
tree = self.data[tree_geom_type].sindex
# also do a single query to ensure the index is actually
# generated and used
tree.query(
self.data[tree_geom_type].geometry.values.data[0]
)
tree.query(self.data[tree_geom_type].geometry.values.data[0])
class BenchQuery:
@@ -103,7 +101,4 @@ class BenchQuery:
def time_query(self, predicate, input_geom_type, tree_geom_type):
tree = self.data[tree_geom_type].sindex
for geom in self.data[input_geom_type].geometry.values.data:
tree.query(
geom,
predicate=predicate
)
tree.query(geom, predicate=predicate)
+16 -10
View File
@@ -7,22 +7,28 @@ import numpy as np
class Bench:
param_names = ['op']
params = [('intersects', 'contains', 'within')]
param_names = ["op"]
params = [("intersects", "contains", "within")]
def setup(self, *args):
triangles = GeoSeries(
[Polygon([(random.random(), random.random()) for _ in range(3)])
for _ in range(1000)])
[
Polygon([(random.random(), random.random()) for _ in range(3)])
for _ in range(1000)
]
)
points = GeoSeries(
[Point(x, y) for x, y in zip(np.random.random(10000),
np.random.random(10000))])
[
Point(x, y)
for x, y in zip(np.random.random(10000), np.random.random(10000))
]
)
df1 = GeoDataFrame({'val1': np.random.randn(len(triangles)),
'geometry': triangles})
df2 = GeoDataFrame({'val1': np.random.randn(len(points)),
'geometry': points})
df1 = GeoDataFrame(
{"val1": np.random.randn(len(triangles)), "geometry": triangles}
)
df2 = GeoDataFrame({"val1": np.random.randn(len(points)), "geometry": points})
self.df1, self.df2 = df1, df2
+5 -6
View File
@@ -5,17 +5,16 @@ from shapely.geometry import Point
class CRS:
def setup(self):
nybb = read_file(datasets.get_path('nybb'))
self.long_nybb = GeoDataFrame(pd.concat(10 * [nybb]),
crs=nybb.crs)
nybb = read_file(datasets.get_path("nybb"))
self.long_nybb = GeoDataFrame(pd.concat(10 * [nybb]), crs=nybb.crs)
num_points = 20000
longitudes = np.random.rand(num_points) - 120
latitudes = np.random.rand(num_points) + 38
self.point_df = GeoSeries([Point(x, y) for (x, y)
in zip(longitudes, latitudes)])
self.point_df = GeoSeries(
[Point(x, y) for (x, y) in zip(longitudes, latitudes)]
)
self.point_df.crs = {"init": "epsg:4326"}
def time_transform_wgs84(self):
+7 -7
View File
@@ -20,16 +20,16 @@ import geopandas as gpd
np.random.seed(1)
DPI = 100
path_nybb = gpd.datasets.get_path('nybb')
path_nybb = gpd.datasets.get_path("nybb")
boros = GeoDataFrame.from_file(path_nybb)
boros = boros.set_index('BoroCode')
boros = boros.set_index("BoroCode")
boros
##############################################################################
# Next, we'll plot the raw data
ax = boros.plot()
plt.xticks(rotation=90)
plt.savefig('nyc.png', dpi=DPI, bbox_inches='tight')
plt.savefig("nyc.png", dpi=DPI, bbox_inches="tight")
##############################################################################
# We can easily retrieve the convex hull of each shape. This corresponds to
@@ -41,7 +41,7 @@ plt.xticks(rotation=90)
xmin, xmax = plt.gca().get_xlim()
ymin, ymax = plt.gca().get_ylim()
plt.savefig('nyc_hull.png', dpi=DPI, bbox_inches='tight')
plt.savefig("nyc_hull.png", dpi=DPI, bbox_inches="tight")
##############################################################################
# We'll generate some random dots scattered throughout our data, and will
@@ -51,7 +51,7 @@ plt.savefig('nyc_hull.png', dpi=DPI, bbox_inches='tight')
N = 2000 # number of random points
R = 2000 # radius of buffer in feet
#xmin, xmax, ymin, ymax = 900000, 1080000, 120000, 280000
# xmin, xmax, ymin, ymax = 900000, 1080000, 120000, 280000
xc = (xmax - xmin) * np.random.random(N) + xmin
yc = (ymax - ymin) * np.random.random(N) + ymin
pts = GeoSeries([Point(x, y) for x, y in zip(xc, yc)])
@@ -59,7 +59,7 @@ mp = pts.buffer(R).unary_union
boros_with_holes = boros.geometry - mp
boros_with_holes.plot()
plt.xticks(rotation=90)
plt.savefig('boros_with_holes.png', dpi=DPI, bbox_inches='tight')
plt.savefig("boros_with_holes.png", dpi=DPI, bbox_inches="tight")
##############################################################################
# Finally, we'll show the holes that were taken out of our boroughs.
@@ -67,5 +67,5 @@ plt.savefig('boros_with_holes.png', dpi=DPI, bbox_inches='tight')
holes = boros.geometry & mp
holes.plot()
plt.xticks(rotation=90)
plt.savefig('holes.png', dpi=DPI, bbox_inches='tight')
plt.savefig("holes.png", dpi=DPI, bbox_inches="tight")
plt.show()
+1 -3
View File
@@ -17,9 +17,7 @@ s = geopandas.GeoSeries(
]
)
fix, axs = plt.subplots(
3, 2, figsize=(12, 12), sharex=True, sharey=True
)
fix, axs = plt.subplots(3, 2, figsize=(12, 12), sharex=True, sharey=True)
for ax in axs.flatten():
s.plot(ax=ax)
ax.set(xticks=[], yticks=[])
@@ -23,9 +23,9 @@
"source": [
"import geopandas\n",
"\n",
"nybb = geopandas.read_file(geopandas.datasets.get_path('nybb'))\n",
"world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))\n",
"cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))"
"nybb = geopandas.read_file(geopandas.datasets.get_path(\"nybb\"))\n",
"world = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_lowres\"))\n",
"cities = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_cities\"))"
]
},
{
@@ -73,14 +73,14 @@
"metadata": {},
"outputs": [],
"source": [
"nybb.explore( \n",
" column=\"BoroName\", # make choropleth based on \"BoroName\" column\n",
" tooltip=\"BoroName\", # show \"BoroName\" value in tooltip (on hover)\n",
" popup=True, # show all values in popup (on click)\n",
" tiles=\"CartoDB positron\", # use \"CartoDB positron\" tiles\n",
" cmap=\"Set1\", # use \"Set1\" matplotlib colormap\n",
" style_kwds=dict(color=\"black\") # use black outline\n",
" )"
"nybb.explore(\n",
" column=\"BoroName\", # make choropleth based on \"BoroName\" column\n",
" tooltip=\"BoroName\", # show \"BoroName\" value in tooltip (on hover)\n",
" popup=True, # show all values in popup (on click)\n",
" tiles=\"CartoDB positron\", # use \"CartoDB positron\" tiles\n",
" cmap=\"Set1\", # use \"Set1\" matplotlib colormap\n",
" style_kwds=dict(color=\"black\"), # use black outline\n",
")"
]
},
{
@@ -101,24 +101,26 @@
"import folium\n",
"\n",
"m = world.explore(\n",
" column=\"pop_est\", # make choropleth based on \"BoroName\" column\n",
" scheme=\"naturalbreaks\", # use mapclassify's natural breaks scheme\n",
" legend=True, # show legend\n",
" k=10, # use 10 bins\n",
" legend_kwds=dict(colorbar=False), # do not use colorbar\n",
" name=\"countries\" # name of the layer in the map\n",
" column=\"pop_est\", # make choropleth based on \"BoroName\" column\n",
" scheme=\"naturalbreaks\", # use mapclassify's natural breaks scheme\n",
" legend=True, # show legend\n",
" k=10, # use 10 bins\n",
" legend_kwds=dict(colorbar=False), # do not use colorbar\n",
" name=\"countries\", # name of the layer in the map\n",
")\n",
"\n",
"cities.explore(\n",
" m=m, # pass the map object\n",
" color=\"red\", # use red color on all points\n",
" marker_kwds=dict(radius=10, fill=True), # make marker radius 10px with fill\n",
" tooltip=\"name\", # show \"name\" column in the tooltip\n",
" tooltip_kwds=dict(labels=False), # do not show column label in the tooltip\n",
" name=\"cities\" # name of the layer in the map\n",
" m=m, # pass the map object\n",
" color=\"red\", # use red color on all points\n",
" marker_kwds=dict(radius=10, fill=True), # make marker radius 10px with fill\n",
" tooltip=\"name\", # show \"name\" column in the tooltip\n",
" tooltip_kwds=dict(labels=False), # do not show column label in the tooltip\n",
" name=\"cities\", # name of the layer in the map\n",
")\n",
"\n",
"folium.TileLayer('Stamen Toner', control=True).add_to(m) # use folium to add alternative tiles\n",
"folium.TileLayer(\"Stamen Toner\", control=True).add_to(\n",
" m\n",
") # use folium to add alternative tiles\n",
"folium.LayerControl().add_to(m) # use folium to add layer control\n",
"\n",
"m # show map"
+22 -20
View File
@@ -29,10 +29,10 @@
"import geopandas\n",
"from cartopy import crs as ccrs\n",
"\n",
"path = geopandas.datasets.get_path('naturalearth_lowres')\n",
"path = geopandas.datasets.get_path(\"naturalearth_lowres\")\n",
"df = geopandas.read_file(path)\n",
"# Add a column we'll use later\n",
"df['gdp_pp'] = df['gdp_md_est'] / df['pop_est']"
"df[\"gdp_pp\"] = df[\"gdp_md_est\"] / df[\"pop_est\"]"
]
},
{
@@ -98,8 +98,8 @@
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(subplot_kw={'projection': crs})\n",
"ax.add_geometries(df_ae['geometry'], crs=crs)"
"fig, ax = plt.subplots(subplot_kw={\"projection\": crs})\n",
"ax.add_geometries(df_ae[\"geometry\"], crs=crs)"
]
},
{
@@ -116,17 +116,17 @@
"metadata": {},
"outputs": [],
"source": [
"crs_epsg = ccrs.epsg('3857')\n",
"df_epsg = df.to_crs(epsg='3857')\n",
"crs_epsg = ccrs.epsg(\"3857\")\n",
"df_epsg = df.to_crs(epsg=\"3857\")\n",
"\n",
"# Generate a figure with two axes, one for CartoPy, one for GeoPandas\n",
"fig, axs = plt.subplots(1, 2, subplot_kw={'projection': crs_epsg},\n",
" figsize=(10, 5))\n",
"fig, axs = plt.subplots(1, 2, subplot_kw={\"projection\": crs_epsg}, figsize=(10, 5))\n",
"# Make the CartoPy plot\n",
"axs[0].add_geometries(df_epsg['geometry'], crs=crs_epsg,\n",
" facecolor='white', edgecolor='black')\n",
"axs[0].add_geometries(\n",
" df_epsg[\"geometry\"], crs=crs_epsg, facecolor=\"white\", edgecolor=\"black\"\n",
")\n",
"# Make the GeoPandas plot\n",
"df_epsg.plot(ax=axs[1], color='white', edgecolor='black')"
"df_epsg.plot(ax=axs[1], color=\"white\", edgecolor=\"black\")"
]
},
{
@@ -148,10 +148,11 @@
"outputs": [],
"source": [
"crs_new = ccrs.AlbersEqualArea()\n",
"new_geometries = [crs_new.project_geometry(ii, src_crs=crs)\n",
" for ii in df_ae['geometry'].values]\n",
"new_geometries = [\n",
" crs_new.project_geometry(ii, src_crs=crs) for ii in df_ae[\"geometry\"].values\n",
"]\n",
"\n",
"fig, ax = plt.subplots(subplot_kw={'projection': crs_new})\n",
"fig, ax = plt.subplots(subplot_kw={\"projection\": crs_new})\n",
"ax.add_geometries(new_geometries, crs=crs_new)"
]
},
@@ -170,8 +171,9 @@
"metadata": {},
"outputs": [],
"source": [
"df_aea = geopandas.GeoDataFrame(df['gdp_pp'], geometry=new_geometries,\n",
" crs=crs_new.proj4_init)\n",
"df_aea = geopandas.GeoDataFrame(\n",
" df[\"gdp_pp\"], geometry=new_geometries, crs=crs_new.proj4_init\n",
")\n",
"df_aea.plot()"
]
},
@@ -189,20 +191,20 @@
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"tags": [
"nbsphinx-thumbnail"
]
},
},
"outputs": [],
"source": [
"# Generate a CartoPy figure and add the countries to it\n",
"fig, ax = plt.subplots(subplot_kw={'projection': crs_new})\n",
"fig, ax = plt.subplots(subplot_kw={\"projection\": crs_new})\n",
"ax.add_geometries(new_geometries, crs=crs_new)\n",
"\n",
"# Calculate centroids and plot\n",
"df_aea_centroids = df_aea.geometry.centroid\n",
"# Need to provide \"zorder\" to ensure the points are plotted above the polygons\n",
"df_aea_centroids.plot(ax=ax, markersize=5, color='r', zorder=10)\n",
"df_aea_centroids.plot(ax=ax, markersize=5, color=\"r\", zorder=10)\n",
"\n",
"plt.show()"
]
+57 -27
View File
@@ -35,6 +35,7 @@
],
"source": [
"import mapclassify\n",
"\n",
"mapclassify.__version__"
]
},
@@ -56,6 +57,7 @@
],
"source": [
"import libpysal\n",
"\n",
"libpysal.__version__"
]
},
@@ -180,8 +182,8 @@
"metadata": {},
"outputs": [],
"source": [
"_ = libpysal.examples.load_example('South')\n",
"pth = libpysal.examples.get_path('south.shp')"
"_ = libpysal.examples.load_example(\"South\")\n",
"pth = libpysal.examples.get_path(\"south.shp\")"
]
},
{
@@ -224,9 +226,14 @@
],
"source": [
"%matplotlib inline\n",
"ax = df.plot(column='HR60', scheme='QUANTILES', k=4, \\\n",
" cmap='BuPu', legend=True,\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5)})"
"ax = df.plot(\n",
" column=\"HR60\",\n",
" scheme=\"QUANTILES\",\n",
" k=4,\n",
" cmap=\"BuPu\",\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5)},\n",
")"
]
},
{
@@ -331,10 +338,14 @@
}
],
"source": [
"ax = df.plot(column='HR60', scheme='QUANTILES', k=4, \\\n",
" cmap='BuPu', legend=True,\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5)},\n",
" )"
"ax = df.plot(\n",
" column=\"HR60\",\n",
" scheme=\"QUANTILES\",\n",
" k=4,\n",
" cmap=\"BuPu\",\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5)},\n",
")"
]
},
{
@@ -356,9 +367,14 @@
}
],
"source": [
"ax = df.plot(column='HR60', scheme='QUANTILES', k=4, \\\n",
" cmap='BuPu', legend=True,\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5), 'fmt':\"{:.4f}\"})"
"ax = df.plot(\n",
" column=\"HR60\",\n",
" scheme=\"QUANTILES\",\n",
" k=4,\n",
" cmap=\"BuPu\",\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5), \"fmt\": \"{:.4f}\"},\n",
")"
]
},
{
@@ -380,9 +396,14 @@
}
],
"source": [
"ax = df.plot(column='HR60', scheme='QUANTILES', k=4, \\\n",
" cmap='BuPu', legend=True,\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5), 'fmt':\"{:.0f}\"})"
"ax = df.plot(\n",
" column=\"HR60\",\n",
" scheme=\"QUANTILES\",\n",
" k=4,\n",
" cmap=\"BuPu\",\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5), \"fmt\": \"{:.0f}\"},\n",
")"
]
},
{
@@ -418,10 +439,13 @@
}
],
"source": [
"ax = df.plot(column='HR60', scheme='BoxPlot', \\\n",
" cmap='BuPu', legend=True,\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5),\n",
" 'fmt': \"{:.0f}\"})"
"ax = df.plot(\n",
" column=\"HR60\",\n",
" scheme=\"BoxPlot\",\n",
" cmap=\"BuPu\",\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5), \"fmt\": \"{:.0f}\"},\n",
")"
]
},
{
@@ -451,7 +475,7 @@
],
"source": [
"bp = mapclassify.BoxPlot(df.HR60)\n",
"bp\n"
"bp"
]
},
{
@@ -512,10 +536,13 @@
}
],
"source": [
"ax = df.plot(column='HR60', scheme='BoxPlot', \\\n",
" cmap='BuPu', legend=True,\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5),\n",
" 'interval': True})"
"ax = df.plot(\n",
" column=\"HR60\",\n",
" scheme=\"BoxPlot\",\n",
" cmap=\"BuPu\",\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5), \"interval\": True},\n",
")"
]
},
{
@@ -544,9 +571,12 @@
}
],
"source": [
"ax = df.plot(column='STATE_NAME', categorical=True, legend=True, \\\n",
" legend_kwds={'loc': 'center left', 'bbox_to_anchor':(1,0.5),\n",
" 'fmt': \"{:.0f}\"}) # fmt is ignored for categorical data"
"ax = df.plot(\n",
" column=\"STATE_NAME\",\n",
" categorical=True,\n",
" legend=True,\n",
" legend_kwds={\"loc\": \"center left\", \"bbox_to_anchor\": (1, 0.5), \"fmt\": \"{:.0f}\"},\n",
") # fmt is ignored for categorical data"
]
}
],
+33 -13
View File
@@ -259,7 +259,7 @@
"\n",
"pth = ps.examples.get_path(\"columbus.shp\")\n",
"tracts = gpd.GeoDataFrame.from_file(pth)\n",
"print('Observations, Attributes:',tracts.shape)\n",
"print(\"Observations, Attributes:\", tracts.shape)\n",
"tracts.head()"
]
},
@@ -294,10 +294,10 @@
],
"source": [
"# Let's take a look at how the CRIME variable is distributed with a histogram\n",
"tracts['CRIME'].hist(bins=20)\n",
"plt.xlabel('CRIME\\nResidential burglaries and vehicle thefts per 1000 households')\n",
"plt.ylabel('Number of neighbourhoods')\n",
"plt.title('Distribution of neighbourhoods by crime rate in Columbus, OH')\n",
"tracts[\"CRIME\"].hist(bins=20)\n",
"plt.xlabel(\"CRIME\\nResidential burglaries and vehicle thefts per 1000 households\")\n",
"plt.ylabel(\"Number of neighbourhoods\")\n",
"plt.title(\"Distribution of neighbourhoods by crime rate in Columbus, OH\")\n",
"plt.show()"
]
},
@@ -345,7 +345,7 @@
}
],
"source": [
"tracts.plot(column='CRIME', cmap='OrRd', edgecolor='k', legend=True)"
"tracts.plot(column=\"CRIME\", cmap=\"OrRd\", edgecolor=\"k\", legend=True)"
]
},
{
@@ -400,7 +400,9 @@
],
"source": [
"# Splitting the data in three shows some spatial clustering around the center\n",
"tracts.plot(column='CRIME', scheme='quantiles', k=3, cmap='OrRd', edgecolor='k', legend=True)"
"tracts.plot(\n",
" column=\"CRIME\", scheme=\"quantiles\", k=3, cmap=\"OrRd\", edgecolor=\"k\", legend=True\n",
")"
]
},
{
@@ -438,7 +440,9 @@
],
"source": [
"# We can also see where the top and bottom halves are located\n",
"tracts.plot(column='CRIME', scheme='quantiles', k=2, cmap='OrRd', edgecolor='k', legend=True)"
"tracts.plot(\n",
" column=\"CRIME\", scheme=\"quantiles\", k=2, cmap=\"OrRd\", edgecolor=\"k\", legend=True\n",
")"
]
},
{
@@ -483,7 +487,14 @@
}
],
"source": [
"tracts.plot(column='CRIME', scheme='equal_interval', k=4, cmap='OrRd', edgecolor='k', legend=True)"
"tracts.plot(\n",
" column=\"CRIME\",\n",
" scheme=\"equal_interval\",\n",
" k=4,\n",
" cmap=\"OrRd\",\n",
" edgecolor=\"k\",\n",
" legend=True,\n",
")"
]
},
{
@@ -521,7 +532,7 @@
],
"source": [
"# No legend here as we'd be out of space\n",
"tracts.plot(column='CRIME', scheme='equal_interval', k=12, cmap='OrRd', edgecolor='k')"
"tracts.plot(column=\"CRIME\", scheme=\"equal_interval\", k=12, cmap=\"OrRd\", edgecolor=\"k\")"
]
},
{
@@ -567,7 +578,14 @@
],
"source": [
"# Compare this to the previous 3-bin figure with quantiles\n",
"tracts.plot(column='CRIME', scheme='natural_breaks', k=3, cmap='OrRd', edgecolor='k', legend=True)"
"tracts.plot(\n",
" column=\"CRIME\",\n",
" scheme=\"natural_breaks\",\n",
" k=3,\n",
" cmap=\"OrRd\",\n",
" edgecolor=\"k\",\n",
" legend=True,\n",
")"
]
},
{
@@ -793,10 +811,12 @@
" returns a list of their Maximum P bin number.\n",
" \"\"\"\n",
" from mapclassify import MaxP\n",
"\n",
" binning = MaxP(values, k=k)\n",
" return binning.yb\n",
"\n",
"tracts['Max_P'] = max_p(tracts['CRIME'].values, k=5)\n",
"\n",
"tracts[\"Max_P\"] = max_p(tracts[\"CRIME\"].values, k=5)\n",
"tracts.head()"
]
},
@@ -829,7 +849,7 @@
}
],
"source": [
"tracts.plot(column='Max_P', cmap='OrRd', edgecolor='k', categorical=True, legend=True)"
"tracts.plot(column=\"Max_P\", cmap=\"OrRd\", edgecolor=\"k\", categorical=True, legend=True)"
]
},
{
@@ -44,10 +44,13 @@
"outputs": [],
"source": [
"df = pd.DataFrame(\n",
" {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],\n",
" 'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],\n",
" 'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],\n",
" 'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86]})"
" {\n",
" \"City\": [\"Buenos Aires\", \"Brasilia\", \"Santiago\", \"Bogota\", \"Caracas\"],\n",
" \"Country\": [\"Argentina\", \"Brazil\", \"Chile\", \"Colombia\", \"Venezuela\"],\n",
" \"Latitude\": [-34.58, -15.78, -33.45, 4.60, 10.48],\n",
" \"Longitude\": [-58.66, -47.91, -70.66, -74.08, -66.86],\n",
" }\n",
")"
]
},
{
@@ -69,7 +72,8 @@
"outputs": [],
"source": [
"gdf = geopandas.GeoDataFrame(\n",
" df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude))"
" df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude)\n",
")"
]
},
{
@@ -107,14 +111,13 @@
},
"outputs": [],
"source": [
"world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))\n",
"world = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_lowres\"))\n",
"\n",
"# We restrict to South America.\n",
"ax = world[world.continent == 'South America'].plot(\n",
" color='white', edgecolor='black')\n",
"ax = world[world.continent == \"South America\"].plot(color=\"white\", edgecolor=\"black\")\n",
"\n",
"# We can now plot our ``GeoDataFrame``.\n",
"gdf.plot(ax=ax, color='red')\n",
"gdf.plot(ax=ax, color=\"red\")\n",
"\n",
"plt.show()"
]
@@ -136,11 +139,18 @@
"outputs": [],
"source": [
"df = pd.DataFrame(\n",
" {'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],\n",
" 'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],\n",
" 'Coordinates': ['POINT(-58.66 -34.58)', 'POINT(-47.91 -15.78)',\n",
" 'POINT(-70.66 -33.45)', 'POINT(-74.08 4.60)',\n",
" 'POINT(-66.86 10.48)']})"
" {\n",
" \"City\": [\"Buenos Aires\", \"Brasilia\", \"Santiago\", \"Bogota\", \"Caracas\"],\n",
" \"Country\": [\"Argentina\", \"Brazil\", \"Chile\", \"Colombia\", \"Venezuela\"],\n",
" \"Coordinates\": [\n",
" \"POINT(-58.66 -34.58)\",\n",
" \"POINT(-47.91 -15.78)\",\n",
" \"POINT(-70.66 -33.45)\",\n",
" \"POINT(-74.08 4.60)\",\n",
" \"POINT(-66.86 10.48)\",\n",
" ],\n",
" }\n",
")"
]
},
{
@@ -159,7 +169,7 @@
"source": [
"from shapely import wkt\n",
"\n",
"df['Coordinates'] = geopandas.GeoSeries.from_wkt(df['Coordinates'])"
"df[\"Coordinates\"] = geopandas.GeoSeries.from_wkt(df[\"Coordinates\"])"
]
},
{
@@ -176,7 +186,7 @@
"metadata": {},
"outputs": [],
"source": [
"gdf = geopandas.GeoDataFrame(df, geometry='Coordinates')\n",
"gdf = geopandas.GeoDataFrame(df, geometry=\"Coordinates\")\n",
"\n",
"print(gdf.head())"
]
@@ -195,10 +205,9 @@
"metadata": {},
"outputs": [],
"source": [
"ax = world[world.continent == 'South America'].plot(\n",
" color='white', edgecolor='black')\n",
"ax = world[world.continent == \"South America\"].plot(color=\"white\", edgecolor=\"black\")\n",
"\n",
"gdf.plot(ax=ax, color='red')\n",
"gdf.plot(ax=ax, color=\"red\")\n",
"\n",
"plt.show()"
]
@@ -43,7 +43,12 @@
"outputs": [],
"source": [
"# Create sampling points\n",
"points = [Point(625466, 5621289), Point(626082, 5621627), Point(627116, 5621680), Point(625095, 5622358)]\n",
"points = [\n",
" Point(625466, 5621289),\n",
" Point(626082, 5621627),\n",
" Point(627116, 5621680),\n",
" Point(625095, 5622358),\n",
"]\n",
"gdf = geopandas.GeoDataFrame([1, 2, 3, 4], geometry=points, crs=32630)"
]
},
@@ -79,7 +84,7 @@
"metadata": {},
"outputs": [],
"source": [
"src = rasterio.open('s2a_l2a_fishbourne.tif')"
"src = rasterio.open(\"s2a_l2a_fishbourne.tif\")"
]
},
{
@@ -105,8 +110,8 @@
"fig, ax = plt.subplots()\n",
"\n",
"# transform rasterio plot to real world coords\n",
"extent=[src.bounds[0], src.bounds[2], src.bounds[1], src.bounds[3]]\n",
"ax = rasterio.plot.show(src, extent=extent, ax=ax, cmap='pink')\n",
"extent = [src.bounds[0], src.bounds[2], src.bounds[1], src.bounds[3]]\n",
"ax = rasterio.plot.show(src, extent=extent, ax=ax, cmap=\"pink\")\n",
"\n",
"gdf.plot(ax=ax)"
]
@@ -128,7 +133,7 @@
"metadata": {},
"outputs": [],
"source": [
"coord_list = [(x,y) for x,y in zip(gdf['geometry'].x , gdf['geometry'].y)]"
"coord_list = [(x, y) for x, y in zip(gdf[\"geometry\"].x, gdf[\"geometry\"].y)]"
]
},
{
@@ -144,7 +149,7 @@
"metadata": {},
"outputs": [],
"source": [
"gdf['value'] = [x for x in src.sample(coord_list)]\n",
"gdf[\"value\"] = [x for x in src.sample(coord_list)]\n",
"gdf.head()"
]
}
+26 -15
View File
@@ -39,7 +39,7 @@
},
"outputs": [],
"source": [
"nybb = gpd.read_file(gpd.datasets.get_path('nybb'))\n",
"nybb = gpd.read_file(gpd.datasets.get_path(\"nybb\"))\n",
"nybb = nybb.to_crs(32619) # Convert the dataset to a coordinate\n",
"# system which uses meters\n",
"\n",
@@ -65,8 +65,10 @@
"source": [
"from shapely.geometry.point import Point\n",
"\n",
"points = gpd.GeoSeries([Point(-73.5, 40.5), Point(-74.5, 40.5)], crs=4326) # Geographic WGS 84 - degrees\n",
"points = points.to_crs(32619) # Projected WGS 84 - meters"
"points = gpd.GeoSeries(\n",
" [Point(-73.5, 40.5), Point(-74.5, 40.5)], crs=4326\n",
") # Geographic WGS 84 - degrees\n",
"points = points.to_crs(32619) # Projected WGS 84 - meters"
]
},
{
@@ -100,7 +102,7 @@
},
"outputs": [],
"source": [
"nybb = gpd.read_file(gpd.datasets.get_path('nybb'))\n",
"nybb = gpd.read_file(gpd.datasets.get_path(\"nybb\"))\n",
"nybb = nybb.to_crs(4326) # Using geographic WGS 84\n",
"\n",
"ax = nybb.plot()\n",
@@ -130,7 +132,7 @@
"metadata": {},
"outputs": [],
"source": [
"nybb = gpd.read_file(gpd.datasets.get_path('nybb'))\n",
"nybb = gpd.read_file(gpd.datasets.get_path(\"nybb\"))\n",
"\n",
"ax = nybb.plot()\n",
"ax.add_artist(ScaleBar(1, dimension=\"imperial-length\", units=\"ft\"))"
@@ -151,28 +153,37 @@
},
"outputs": [],
"source": [
"nybb = gpd.read_file(gpd.datasets.get_path('nybb')).to_crs(32619)\n",
"nybb = gpd.read_file(gpd.datasets.get_path(\"nybb\")).to_crs(32619)\n",
"ax = nybb.plot()\n",
"\n",
"# Position and layout\n",
"scale1 = ScaleBar(\n",
"dx=1, label='Scale 1',\n",
" location='upper left', # in relation to the whole plot\n",
" label_loc='left', scale_loc='bottom' # in relation to the line\n",
" dx=1,\n",
" label=\"Scale 1\",\n",
" location=\"upper left\", # in relation to the whole plot\n",
" label_loc=\"left\",\n",
" scale_loc=\"bottom\", # in relation to the line\n",
")\n",
"\n",
"# Color\n",
"scale2 = ScaleBar(\n",
" dx=1, label='Scale 2', location='center', \n",
" color='#b32400', box_color='yellow',\n",
" box_alpha=0.8 # Slightly transparent box\n",
" dx=1,\n",
" label=\"Scale 2\",\n",
" location=\"center\",\n",
" color=\"#b32400\",\n",
" box_color=\"yellow\",\n",
" box_alpha=0.8, # Slightly transparent box\n",
")\n",
"\n",
"# Font and text formatting\n",
"scale3 = ScaleBar(\n",
" dx=1, label='Scale 3',\n",
" font_properties={'family':'serif', 'size': 'large'}, # For more information, see the cell below\n",
" scale_formatter=lambda value, unit: f'> {value} {unit} <'\n",
" dx=1,\n",
" label=\"Scale 3\",\n",
" font_properties={\n",
" \"family\": \"serif\",\n",
" \"size\": \"large\",\n",
" }, # For more information, see the cell below\n",
" scale_formatter=lambda value, unit: f\"> {value} {unit} <\",\n",
")\n",
"\n",
"ax.add_artist(scale1)\n",
+16 -11
View File
@@ -35,16 +35,21 @@
"from geopandas.tools import overlay\n",
"\n",
"# NYC Boros\n",
"zippath = datasets.get_path('nybb')\n",
"zippath = datasets.get_path(\"nybb\")\n",
"polydf = read_file(zippath)\n",
"\n",
"# Generate some circles\n",
"b = [int(x) for x in polydf.total_bounds]\n",
"N = 10\n",
"polydf2 = GeoDataFrame([\n",
" {'geometry': Point(x, y).buffer(10000), 'value1': x + y, 'value2': x - y}\n",
" for x, y in zip(range(b[0], b[2], int((b[2] - b[0]) / N)),\n",
" range(b[1], b[3], int((b[3] - b[1]) / N)))])"
"polydf2 = GeoDataFrame(\n",
" [\n",
" {\"geometry\": Point(x, y).buffer(10000), \"value1\": x + y, \"value2\": x - y}\n",
" for x, y in zip(\n",
" range(b[0], b[2], int((b[2] - b[0]) / N)),\n",
" range(b[1], b[3], int((b[3] - b[1]) / N)),\n",
" )\n",
" ]\n",
")"
],
"outputs": [],
"metadata": {}
@@ -76,7 +81,7 @@
"cell_type": "code",
"execution_count": null,
"source": [
"polydf2.plot(cmap='tab20b')"
"polydf2.plot(cmap=\"tab20b\")"
],
"outputs": [],
"metadata": {}
@@ -107,7 +112,7 @@
"execution_count": null,
"source": [
"newdf = polydf.overlay(polydf2, how=\"intersection\")\n",
"newdf.plot(cmap='tab20b')"
"newdf.plot(cmap=\"tab20b\")"
],
"outputs": [],
"metadata": {}
@@ -158,7 +163,7 @@
"execution_count": null,
"source": [
"newdf = polydf.overlay(polydf2, how=\"union\")\n",
"newdf.plot(cmap='tab20b')"
"newdf.plot(cmap=\"tab20b\")"
],
"outputs": [],
"metadata": {}
@@ -168,7 +173,7 @@
"execution_count": null,
"source": [
"newdf = polydf.overlay(polydf2, how=\"identity\")\n",
"newdf.plot(cmap='tab20b')"
"newdf.plot(cmap=\"tab20b\")"
],
"outputs": [],
"metadata": {}
@@ -178,7 +183,7 @@
"execution_count": null,
"source": [
"newdf = polydf.overlay(polydf2, how=\"symmetric_difference\")\n",
"newdf.plot(cmap='tab20b')"
"newdf.plot(cmap=\"tab20b\")"
],
"outputs": [],
"metadata": {
@@ -192,7 +197,7 @@
"execution_count": null,
"source": [
"newdf = polydf.overlay(polydf2, how=\"difference\")\n",
"newdf.plot(cmap='tab20b')"
"newdf.plot(cmap=\"tab20b\")"
],
"outputs": [],
"metadata": {}
@@ -41,8 +41,8 @@
"metadata": {},
"outputs": [],
"source": [
"df = geopandas.read_file(geopandas.datasets.get_path('nybb'))\n",
"ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')"
"df = geopandas.read_file(geopandas.datasets.get_path(\"nybb\"))\n",
"ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")"
]
},
{
@@ -108,7 +108,7 @@
},
"outputs": [],
"source": [
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')\n",
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")\n",
"cx.add_basemap(ax)"
]
},
@@ -127,7 +127,7 @@
"metadata": {},
"outputs": [],
"source": [
"ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')\n",
"ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")\n",
"cx.add_basemap(ax, crs=df.crs)"
]
},
@@ -164,7 +164,7 @@
"metadata": {},
"outputs": [],
"source": [
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')\n",
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")\n",
"cx.add_basemap(ax, zoom=12)"
]
},
@@ -190,7 +190,7 @@
"metadata": {},
"outputs": [],
"source": [
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')\n",
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")\n",
"cx.add_basemap(ax, source=cx.providers.Stamen.TonerLite)\n",
"ax.set_axis_off()"
]
@@ -218,7 +218,7 @@
"metadata": {},
"outputs": [],
"source": [
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')\n",
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")\n",
"cx.add_basemap(ax, source=cx.providers.Stamen.TonerLite)\n",
"cx.add_basemap(ax, source=cx.providers.Stamen.TonerLabels)"
]
@@ -237,7 +237,7 @@
"metadata": {},
"outputs": [],
"source": [
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')\n",
"ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor=\"k\")\n",
"cx.add_basemap(ax, source=cx.providers.Stamen.Watercolor, zoom=12)\n",
"cx.add_basemap(ax, source=cx.providers.Stamen.TonerLabels, zoom=10)"
]
+14 -6
View File
@@ -182,12 +182,20 @@
" map.add_child(\n",
" folium.Marker(\n",
" location=coordinates,\n",
" popup=\n",
" \"Year: \" + str(geo_df.Year[i]) + \"<br>\"\n",
" + \"Name: \" + str(geo_df.Name[i]) + \"<br>\"\n",
" + \"Country: \" + str(geo_df.Country[i]) + \"<br>\"\n",
" + \"Type: \" + str(geo_df.Type[i]) + \"<br>\"\n",
" + \"Coordinates: \" + str(geo_df_list[i]),\n",
" popup=\"Year: \"\n",
" + str(geo_df.Year[i])\n",
" + \"<br>\"\n",
" + \"Name: \"\n",
" + str(geo_df.Name[i])\n",
" + \"<br>\"\n",
" + \"Country: \"\n",
" + str(geo_df.Country[i])\n",
" + \"<br>\"\n",
" + \"Type: \"\n",
" + str(geo_df.Type[i])\n",
" + \"<br>\"\n",
" + \"Coordinates: \"\n",
" + str(geo_df_list[i]),\n",
" icon=folium.Icon(color=\"%s\" % type_color),\n",
" )\n",
" )\n",
+15 -21
View File
@@ -28,15 +28,9 @@
"import geopandas\n",
"import geoplot\n",
"\n",
"world = geopandas.read_file(\n",
" geopandas.datasets.get_path('naturalearth_lowres')\n",
")\n",
"boroughs = geopandas.read_file(\n",
" geoplot.datasets.get_path('nyc_boroughs')\n",
")\n",
"collisions = geopandas.read_file(\n",
" geoplot.datasets.get_path('nyc_injurious_collisions')\n",
")"
"world = geopandas.read_file(geopandas.datasets.get_path(\"naturalearth_lowres\"))\n",
"boroughs = geopandas.read_file(geoplot.datasets.get_path(\"nyc_boroughs\"))\n",
"collisions = geopandas.read_file(geoplot.datasets.get_path(\"nyc_injurious_collisions\"))"
]
},
{
@@ -76,9 +70,7 @@
"outputs": [],
"source": [
"# use the Orthographic map projection (e.g. a world globe)\n",
"ax = geoplot.polyplot(\n",
" world, projection=geoplot.crs.Orthographic(), figsize=(8, 4)\n",
")\n",
"ax = geoplot.polyplot(world, projection=geoplot.crs.Orthographic(), figsize=(8, 4))\n",
"ax.outline_patch.set_visible(True)"
]
},
@@ -101,13 +93,13 @@
"outputs": [],
"source": [
"import mapclassify\n",
"gpd_per_person = world['gdp_md_est'] / world['pop_est']\n",
"\n",
"gpd_per_person = world[\"gdp_md_est\"] / world[\"pop_est\"]\n",
"scheme = mapclassify.Quantiles(gpd_per_person, k=5)\n",
"\n",
"# Note: this code sample requires geoplot>=0.4.0.\n",
"geoplot.choropleth(\n",
" world, hue=gpd_per_person, scheme=scheme,\n",
" cmap='Greens', figsize=(8, 4)\n",
" world, hue=gpd_per_person, scheme=scheme, cmap=\"Greens\", figsize=(8, 4)\n",
")"
]
},
@@ -128,10 +120,9 @@
"source": [
"africa = world.query('continent == \"Africa\"')\n",
"ax = geoplot.cartogram(\n",
" africa, scale='pop_est', limits=(0.2, 1),\n",
" edgecolor='None', figsize=(7, 8)\n",
" africa, scale=\"pop_est\", limits=(0.2, 1), edgecolor=\"None\", figsize=(7, 8)\n",
")\n",
"geoplot.polyplot(africa, edgecolor='gray', ax=ax)"
"geoplot.polyplot(africa, edgecolor=\"gray\", ax=ax)"
]
},
{
@@ -154,9 +145,12 @@
"outputs": [],
"source": [
"ax = geoplot.kdeplot(\n",
" collisions.head(1000), clip=boroughs.geometry,\n",
" shade=True, cmap='Reds',\n",
" projection=geoplot.crs.AlbersEqualArea())\n",
" collisions.head(1000),\n",
" clip=boroughs.geometry,\n",
" shade=True,\n",
" cmap=\"Reds\",\n",
" projection=geoplot.crs.AlbersEqualArea(),\n",
")\n",
"geoplot.polyplot(boroughs, ax=ax, zorder=1)"
]
},
@@ -33,7 +33,7 @@
"metadata": {},
"outputs": [],
"source": [
"path = gpd.datasets.get_path('nybb')\n",
"path = gpd.datasets.get_path(\"nybb\")\n",
"df = gpd.read_file(path)\n",
"df.head()"
]
@@ -119,7 +119,7 @@
"metadata": {},
"outputs": [],
"source": [
"m = folium.Map(location=[40.70, -73.94], zoom_start=10, tiles='CartoDB positron')\n",
"m = folium.Map(location=[40.70, -73.94], zoom_start=10, tiles=\"CartoDB positron\")\n",
"m"
]
},
@@ -139,12 +139,11 @@
"source": [
"for _, r in df.iterrows():\n",
" # Without simplifying the representation of each borough,\n",
" # the map might not be displayed \n",
" sim_geo = gpd.GeoSeries(r['geometry']).simplify(tolerance=0.001)\n",
" # the map might not be displayed\n",
" sim_geo = gpd.GeoSeries(r[\"geometry\"]).simplify(tolerance=0.001)\n",
" geo_j = sim_geo.to_json()\n",
" geo_j = folium.GeoJson(data=geo_j,\n",
" style_function=lambda x: {'fillColor': 'orange'})\n",
" folium.Popup(r['BoroName']).add_to(geo_j)\n",
" geo_j = folium.GeoJson(data=geo_j, style_function=lambda x: {\"fillColor\": \"orange\"})\n",
" folium.Popup(r[\"BoroName\"]).add_to(geo_j)\n",
" geo_j.add_to(m)\n",
"m"
]
@@ -167,7 +166,7 @@
"df = df.to_crs(epsg=2263)\n",
"\n",
"# Access the centroid attribute of each polygon\n",
"df['centroid'] = df.centroid"
"df[\"centroid\"] = df.centroid"
]
},
{
@@ -189,7 +188,7 @@
"df = df.to_crs(epsg=4326)\n",
"\n",
"# Centroid column\n",
"df['centroid'] = df['centroid'].to_crs(epsg=4326)\n",
"df[\"centroid\"] = df[\"centroid\"].to_crs(epsg=4326)\n",
"\n",
"df.head()"
]
@@ -201,10 +200,12 @@
"outputs": [],
"source": [
"for _, r in df.iterrows():\n",
" lat = r['centroid'].y\n",
" lon = r['centroid'].x\n",
" folium.Marker(location=[lat, lon],\n",
" popup='length: {} <br> area: {}'.format(r['Shape_Leng'], r['Shape_Area'])).add_to(m)\n",
" lat = r[\"centroid\"].y\n",
" lon = r[\"centroid\"].x\n",
" folium.Marker(\n",
" location=[lat, lon],\n",
" popup=\"length: {} <br> area: {}\".format(r[\"Shape_Leng\"], r[\"Shape_Area\"]),\n",
" ).add_to(m)\n",
"\n",
"m"
]
+10 -5
View File
@@ -107,16 +107,21 @@
"from geopandas import datasets, GeoDataFrame, read_file\n",
"\n",
"# NYC Boros\n",
"zippath = datasets.get_path('nybb')\n",
"zippath = datasets.get_path(\"nybb\")\n",
"polydf = read_file(zippath)\n",
"\n",
"# Generate some points\n",
"b = [int(x) for x in polydf.total_bounds]\n",
"N = 8\n",
"pointdf = GeoDataFrame([\n",
" {'geometry': Point(x, y), 'value1': x + y, 'value2': x - y}\n",
" for x, y in zip(range(b[0], b[2], int((b[2] - b[0]) / N)),\n",
" range(b[1], b[3], int((b[3] - b[1]) / N)))])\n",
"pointdf = GeoDataFrame(\n",
" [\n",
" {\"geometry\": Point(x, y), \"value1\": x + y, \"value2\": x - y}\n",
" for x, y in zip(\n",
" range(b[0], b[2], int((b[2] - b[0]) / N)),\n",
" range(b[1], b[3], int((b[3] - b[1]) / N)),\n",
" )\n",
" ]\n",
")\n",
"\n",
"# Make sure they're using the same projection reference\n",
"pointdf.crs = polydf.crs"
+24 -15
View File
@@ -136,8 +136,8 @@
"metadata": {},
"outputs": [],
"source": [
"gdf['boundary'] = gdf.boundary\n",
"gdf['boundary']"
"gdf[\"boundary\"] = gdf.boundary\n",
"gdf[\"boundary\"]"
]
},
{
@@ -155,8 +155,8 @@
"metadata": {},
"outputs": [],
"source": [
"gdf['centroid'] = gdf.centroid\n",
"gdf['centroid']"
"gdf[\"centroid\"] = gdf.centroid\n",
"gdf[\"centroid\"]"
]
},
{
@@ -174,9 +174,9 @@
"metadata": {},
"outputs": [],
"source": [
"first_point = gdf['centroid'].iloc[0]\n",
"gdf['distance'] = gdf['centroid'].distance(first_point)\n",
"gdf['distance']"
"first_point = gdf[\"centroid\"].iloc[0]\n",
"gdf[\"distance\"] = gdf[\"centroid\"].distance(first_point)\n",
"gdf[\"distance\"]"
]
},
{
@@ -194,7 +194,7 @@
"metadata": {},
"outputs": [],
"source": [
"gdf['distance'].mean()"
"gdf[\"distance\"].mean()"
]
},
{
@@ -315,8 +315,10 @@
"metadata": {},
"outputs": [],
"source": [
"ax = gdf[\"convex_hull\"].plot(alpha=.5) # saving the first plot as an axis and setting alpha (transparency) to 0.5\n",
"gdf[\"boundary\"].plot(ax=ax, color=\"white\", linewidth=.5) # passing the first plot and setting linewitdth to 0.5"
"# saving the first plot as an axis and setting alpha (transparency) to 0.5\n",
"ax = gdf[\"convex_hull\"].plot(alpha=0.5)\n",
"# passing the first plot and setting linewitdth to 0.5\n",
"gdf[\"boundary\"].plot(ax=ax, color=\"white\", linewidth=0.5)"
]
},
{
@@ -347,9 +349,12 @@
"metadata": {},
"outputs": [],
"source": [
"ax = gdf[\"buffered\"].plot(alpha=.5) # saving the first plot as an axis and setting alpha (transparency) to 0.5\n",
"gdf[\"buffered_centroid\"].plot(ax=ax, color=\"red\", alpha=.5) # passing the first plot as an axis to the second\n",
"gdf[\"boundary\"].plot(ax=ax, color=\"white\", linewidth=.5) # passing the first plot and setting linewitdth to 0.5"
"# saving the first plot as an axis and setting alpha (transparency) to 0.5\n",
"ax = gdf[\"buffered\"].plot(alpha=0.5)\n",
"# passing the first plot as an axis to the second\n",
"gdf[\"buffered_centroid\"].plot(ax=ax, color=\"red\", alpha=0.5)\n",
"# passing the first plot and setting linewitdth to 0.5\n",
"gdf[\"boundary\"].plot(ax=ax, color=\"white\", linewidth=0.5)"
]
},
{
@@ -446,8 +451,12 @@
"outputs": [],
"source": [
"gdf = gdf.set_geometry(\"buffered_centroid\")\n",
"ax = gdf.plot(\"within\", legend=True, categorical=True, legend_kwds={'loc': \"upper left\"}) # using categorical plot and setting the position of the legend\n",
"gdf[\"boundary\"].plot(ax=ax, color=\"black\", linewidth=.5) # passing the first plot and setting linewitdth to 0.5"
"# using categorical plot and setting the position of the legend\n",
"ax = gdf.plot(\n",
" \"within\", legend=True, categorical=True, legend_kwds={\"loc\": \"upper left\"}\n",
")\n",
"# passing the first plot and setting linewitdth to 0.5\n",
"gdf[\"boundary\"].plot(ax=ax, color=\"black\", linewidth=0.5)"
]
},
{