epymorph 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- epymorph/__init__.py +7 -0
- epymorph/__main__.py +16 -0
- epymorph/adrio/__init__.py +0 -0
- epymorph/adrio/acs5.py +1378 -0
- epymorph/adrio/adrio.py +953 -0
- epymorph/adrio/cdc.py +1826 -0
- epymorph/adrio/commuting_flows.py +283 -0
- epymorph/adrio/csv.py +499 -0
- epymorph/adrio/humidity.py +206 -0
- epymorph/adrio/lodes.py +509 -0
- epymorph/adrio/numpy.py +160 -0
- epymorph/adrio/prism.py +345 -0
- epymorph/adrio/processing.py +1221 -0
- epymorph/adrio/soda.py +602 -0
- epymorph/adrio/us_tiger.py +289 -0
- epymorph/adrio/validation.py +382 -0
- epymorph/attribute.py +614 -0
- epymorph/cache.py +680 -0
- epymorph/cli/__init__.py +0 -0
- epymorph/cli/cache.py +78 -0
- epymorph/cli/main.py +29 -0
- epymorph/compartment_model.py +1873 -0
- epymorph/data/__init__.py +1 -0
- epymorph/data/ipm/__init__.py +22 -0
- epymorph/data/ipm/no.py +14 -0
- epymorph/data/ipm/pei.py +40 -0
- epymorph/data/ipm/seirs.py +50 -0
- epymorph/data/ipm/sirh.py +55 -0
- epymorph/data/ipm/sirs.py +48 -0
- epymorph/data/ipm/sparsemod.py +96 -0
- epymorph/data/mm/__init__.py +22 -0
- epymorph/data/mm/centroids.py +76 -0
- epymorph/data/mm/flat.py +61 -0
- epymorph/data/mm/icecube.py +50 -0
- epymorph/data/mm/no.py +29 -0
- epymorph/data/mm/pei.py +105 -0
- epymorph/data/mm/sparsemod.py +73 -0
- epymorph/data/pei.py +424 -0
- epymorph/data_shape.py +593 -0
- epymorph/data_type.py +185 -0
- epymorph/data_usage.py +258 -0
- epymorph/database.py +1301 -0
- epymorph/error.py +195 -0
- epymorph/event.py +196 -0
- epymorph/geography/__init__.py +0 -0
- epymorph/geography/custom.py +93 -0
- epymorph/geography/scope.py +457 -0
- epymorph/geography/us_census.py +1056 -0
- epymorph/geography/us_geography.py +502 -0
- epymorph/geography/us_tiger.py +1083 -0
- epymorph/initializer.py +786 -0
- epymorph/kit.py +107 -0
- epymorph/log/__init__.py +0 -0
- epymorph/log/file.py +128 -0
- epymorph/log/messaging.py +139 -0
- epymorph/log/movement.py +228 -0
- epymorph/movement_model.py +347 -0
- epymorph/parameter_fitting/__init__.py +0 -0
- epymorph/parameter_fitting/distribution.py +68 -0
- epymorph/parameter_fitting/dynamics.py +19 -0
- epymorph/parameter_fitting/filter/__init__.py +0 -0
- epymorph/parameter_fitting/filter/base_filter.py +50 -0
- epymorph/parameter_fitting/filter/particle.py +32 -0
- epymorph/parameter_fitting/filter/particle_filter.py +296 -0
- epymorph/parameter_fitting/likelihood.py +54 -0
- epymorph/parameter_fitting/output.py +73 -0
- epymorph/parameter_fitting/particlefilter_simulation.py +175 -0
- epymorph/parameter_fitting/perturbation.py +19 -0
- epymorph/parameter_fitting/utils/__init__.py +0 -0
- epymorph/parameter_fitting/utils/data_loader.py +97 -0
- epymorph/parameter_fitting/utils/epymorph_simulation.py +119 -0
- epymorph/parameter_fitting/utils/observations.py +63 -0
- epymorph/parameter_fitting/utils/parameter_estimation.py +49 -0
- epymorph/parameter_fitting/utils/params_perturb.py +43 -0
- epymorph/parameter_fitting/utils/particle_initializer.py +95 -0
- epymorph/parameter_fitting/utils/resampler.py +258 -0
- epymorph/parameter_fitting/utils/utils.py +101 -0
- epymorph/params.py +438 -0
- epymorph/py.typed +0 -0
- epymorph/rume.py +871 -0
- epymorph/simulation.py +991 -0
- epymorph/simulator/__init__.py +0 -0
- epymorph/simulator/basic/__init__.py +0 -0
- epymorph/simulator/basic/basic_simulator.py +171 -0
- epymorph/simulator/basic/ipm_exec.py +437 -0
- epymorph/simulator/basic/mm_exec.py +244 -0
- epymorph/simulator/basic/output.py +213 -0
- epymorph/simulator/world.py +149 -0
- epymorph/simulator/world_list.py +274 -0
- epymorph/strata.py +24 -0
- epymorph/sympy_shim.py +57 -0
- epymorph/time.py +1197 -0
- epymorph/tools/__init__.py +0 -0
- epymorph/tools/data.py +297 -0
- epymorph/tools/ipm_diagram.py +208 -0
- epymorph/tools/out_map.py +551 -0
- epymorph/tools/out_plot.py +423 -0
- epymorph/tools/out_table.py +582 -0
- epymorph/util.py +1036 -0
- epymorph-1.0.0.dist-info/METADATA +57 -0
- epymorph-1.0.0.dist-info/RECORD +104 -0
- epymorph-1.0.0.dist-info/WHEEL +5 -0
- epymorph-1.0.0.dist-info/entry_points.txt +2 -0
- epymorph-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""Tools for rendering geographic maps from epymorph simulation output data."""
|
|
2
|
+
|
|
3
|
+
from itertools import repeat
|
|
4
|
+
from typing import Any, Callable, Iterable, cast
|
|
5
|
+
|
|
6
|
+
import geopandas as gpd
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from matplotlib.axes import Axes
|
|
10
|
+
from matplotlib.cm import ScalarMappable
|
|
11
|
+
from matplotlib.colors import Normalize
|
|
12
|
+
from matplotlib.ticker import EngFormatter
|
|
13
|
+
from pyproj import CRS
|
|
14
|
+
from shapely.geometry import Point
|
|
15
|
+
|
|
16
|
+
from epymorph.compartment_model import QuantityAggregation, QuantitySelection
|
|
17
|
+
from epymorph.error import GeographyError
|
|
18
|
+
from epymorph.geography.scope import GeoAggregation, GeoGroup, GeoSelection
|
|
19
|
+
from epymorph.time import TimeAggregation, TimeSelection
|
|
20
|
+
from epymorph.tools.data import Output, munge
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class NodeLabelRenderer:
|
|
24
|
+
"""
|
|
25
|
+
Customizes rendering of text labels on choropleth maps.
|
|
26
|
+
|
|
27
|
+
The default implementation is very simple, but you may override this class to
|
|
28
|
+
customize. Default implementations of `coords`, `labels`, `colors`, and
|
|
29
|
+
`additional_kwargs` are given so you can override only the aspects you are
|
|
30
|
+
interested in customizing.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
color :
|
|
35
|
+
The default color of the labels. Accepts color formats supported by matplotlib.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
_color: str
|
|
39
|
+
|
|
40
|
+
def __init__(self, color: str = "white"):
|
|
41
|
+
self._color = color
|
|
42
|
+
|
|
43
|
+
def coords(self, data_gdf: pd.DataFrame) -> gpd.GeoSeries:
|
|
44
|
+
"""
|
|
45
|
+
Determine where to draw the labels.
|
|
46
|
+
|
|
47
|
+
Parameters
|
|
48
|
+
----------
|
|
49
|
+
data_gdf :
|
|
50
|
+
The geography/data being rendered.
|
|
51
|
+
|
|
52
|
+
Returns
|
|
53
|
+
-------
|
|
54
|
+
:
|
|
55
|
+
The series of centroids for each row in the data.
|
|
56
|
+
Data must be [`shapely.Point`][] instances.
|
|
57
|
+
"""
|
|
58
|
+
# If we already have centroids in the gdf, use those.
|
|
59
|
+
# Otherwise calculate from the polygon.
|
|
60
|
+
# Note that this will throw a warning if a geographic CRS is used.
|
|
61
|
+
return cast(
|
|
62
|
+
gpd.GeoSeries,
|
|
63
|
+
(
|
|
64
|
+
data_gdf["centroid"]
|
|
65
|
+
if "centroid" in data_gdf.columns
|
|
66
|
+
else data_gdf.geometry.centroid
|
|
67
|
+
),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def labels(self, data_gdf: pd.DataFrame) -> Iterable[str | None]:
|
|
71
|
+
"""
|
|
72
|
+
Determine the text of each label.
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
data_gdf :
|
|
77
|
+
The geography/data being rendered.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
:
|
|
82
|
+
The series of labels for each row in the data.
|
|
83
|
+
Values can be `None` to skip labeling a row.
|
|
84
|
+
"""
|
|
85
|
+
return data_gdf["data"].apply(lambda x: f"{x:.1f}")
|
|
86
|
+
|
|
87
|
+
def colors(
|
|
88
|
+
self,
|
|
89
|
+
data_gdf: pd.DataFrame,
|
|
90
|
+
color_scale: ScalarMappable,
|
|
91
|
+
) -> Iterable[str]:
|
|
92
|
+
"""
|
|
93
|
+
Determine the color of each label.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
data_gdf :
|
|
98
|
+
The geography/data being rendered.
|
|
99
|
+
color_scale :
|
|
100
|
+
A color scale to use.
|
|
101
|
+
|
|
102
|
+
Returns
|
|
103
|
+
-------
|
|
104
|
+
:
|
|
105
|
+
The series of colors for each row in the data.
|
|
106
|
+
Values can be any color format supported by matplotlib.
|
|
107
|
+
"""
|
|
108
|
+
return repeat(self._color, data_gdf["data"].size)
|
|
109
|
+
|
|
110
|
+
def additional_kwargs(self, data_gdf: pd.DataFrame) -> Iterable[dict]:
|
|
111
|
+
"""
|
|
112
|
+
Determine extra keyword arguments to pass to the method drawing labels;
|
|
113
|
+
supports any argument used by [`matplotlib.axes.Axes.annotate`][].
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
data_gdf :
|
|
118
|
+
The geography/data being rendered.
|
|
119
|
+
|
|
120
|
+
Returns
|
|
121
|
+
-------
|
|
122
|
+
:
|
|
123
|
+
The series of dicts containing additional kwargs options for each row in the
|
|
124
|
+
data.
|
|
125
|
+
"""
|
|
126
|
+
return repeat(
|
|
127
|
+
{"ha": "center", "va": "center", "fontsize": 8},
|
|
128
|
+
data_gdf["data"].size,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
def render(
|
|
132
|
+
self,
|
|
133
|
+
ax: Axes,
|
|
134
|
+
data_gdf: pd.DataFrame,
|
|
135
|
+
color_scale: ScalarMappable,
|
|
136
|
+
) -> None:
|
|
137
|
+
"""
|
|
138
|
+
Render labels onto the given matplotlib axes.
|
|
139
|
+
|
|
140
|
+
Parameters
|
|
141
|
+
----------
|
|
142
|
+
ax :
|
|
143
|
+
The axes on which to render.
|
|
144
|
+
data_gdf :
|
|
145
|
+
The geography/data being rendered.
|
|
146
|
+
color_scale :
|
|
147
|
+
The color scale to use.
|
|
148
|
+
"""
|
|
149
|
+
for point, label, color, kwargs in zip(
|
|
150
|
+
self.coords(data_gdf),
|
|
151
|
+
self.labels(data_gdf),
|
|
152
|
+
self.colors(data_gdf, color_scale),
|
|
153
|
+
self.additional_kwargs(data_gdf),
|
|
154
|
+
):
|
|
155
|
+
if label is not None and isinstance(point, Point):
|
|
156
|
+
ax.annotate(label, xy=(point.x, point.y), color=color, **kwargs)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class MapRenderer:
|
|
160
|
+
"""
|
|
161
|
+
Provides methods for rendering an output in choropleth map form.
|
|
162
|
+
|
|
163
|
+
Most commonly, you will use `MapRenderer` starting from a simulation output object
|
|
164
|
+
that supports it:
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
out = BasicSimulation(rume).run()
|
|
168
|
+
out.map.choropleth(...)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Parameters
|
|
172
|
+
----------
|
|
173
|
+
output :
|
|
174
|
+
The output the renderer will use.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
output: Output
|
|
178
|
+
"""The output the renderer will use."""
|
|
179
|
+
|
|
180
|
+
def __init__(self, output: Output):
|
|
181
|
+
self.output = output
|
|
182
|
+
|
|
183
|
+
def geography_data(
|
|
184
|
+
self,
|
|
185
|
+
geo: GeoSelection | GeoAggregation,
|
|
186
|
+
time: TimeSelection | TimeAggregation,
|
|
187
|
+
quantity: QuantitySelection | QuantityAggregation,
|
|
188
|
+
*,
|
|
189
|
+
proj: CRS | str | None = None,
|
|
190
|
+
transform: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
|
|
191
|
+
) -> gpd.GeoDataFrame:
|
|
192
|
+
"""
|
|
193
|
+
Calculate the geo dataframe used for drawing maps merged with the output data
|
|
194
|
+
from the given axis strategies.
|
|
195
|
+
|
|
196
|
+
This is an advanced method that allows you to leverage the data-handling logic
|
|
197
|
+
of `MapRenderer` without necessarily drawing a map.
|
|
198
|
+
|
|
199
|
+
Parameters
|
|
200
|
+
----------
|
|
201
|
+
geo :
|
|
202
|
+
The geographic selection to make on the output data.
|
|
203
|
+
time :
|
|
204
|
+
The time selection to make on the output data.
|
|
205
|
+
quantity :
|
|
206
|
+
The quantity selection to make on the output data.
|
|
207
|
+
proj :
|
|
208
|
+
The projection to use for mapping; if `None` (default) we will
|
|
209
|
+
map using the default projection for the source geography.
|
|
210
|
+
(For US Census, this is NAD83 [https://epsg.org/crs_4269/index.html](https://epsg.org/crs_4269/index.html))
|
|
211
|
+
transform :
|
|
212
|
+
Allows you to specify an arbitrary transform function on the source
|
|
213
|
+
dataframe before we plot it, e.g., to rescale the values.
|
|
214
|
+
The dataframe given as the argument is the result of applying
|
|
215
|
+
all selections and the projection if specified.
|
|
216
|
+
You should return a dataframe with the same format, where the
|
|
217
|
+
data column has been modified for your purposes.
|
|
218
|
+
|
|
219
|
+
Dataframe columns:
|
|
220
|
+
- "geo": the node ID of each polygon
|
|
221
|
+
- "data": the data value from the quantity selection
|
|
222
|
+
|
|
223
|
+
Returns
|
|
224
|
+
-------
|
|
225
|
+
:
|
|
226
|
+
The geo dataframe as a result of applying the axis strategies to the data.
|
|
227
|
+
|
|
228
|
+
Raises
|
|
229
|
+
------
|
|
230
|
+
GeographyError
|
|
231
|
+
If we cannot fetch geography for the type of scope used.
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
# Our result should have three columns: time, node, and a data value
|
|
235
|
+
data_df = munge(self.output, geo, time, quantity)
|
|
236
|
+
if len(data_df["time"].unique()) > 1:
|
|
237
|
+
err = (
|
|
238
|
+
"When drawing a choropleth map, please ensure that you choose a "
|
|
239
|
+
"time aggregation strategy that reduces the time series to a "
|
|
240
|
+
"single point (scalar)."
|
|
241
|
+
)
|
|
242
|
+
raise ValueError(err)
|
|
243
|
+
if len(data_df.columns) > 3:
|
|
244
|
+
err = (
|
|
245
|
+
"When drawing a choropleth map, please ensure that you choose a "
|
|
246
|
+
"quantity strategy that produces a single value column -- either "
|
|
247
|
+
"by selecting a single IPM quantity or aggregating multiple quantities "
|
|
248
|
+
"to one value per geo node."
|
|
249
|
+
)
|
|
250
|
+
raise ValueError(err)
|
|
251
|
+
data_df = data_df.set_axis(["time", "geo", "data"], axis=1)
|
|
252
|
+
|
|
253
|
+
if transform is not None:
|
|
254
|
+
data_df = transform(data_df)
|
|
255
|
+
|
|
256
|
+
return gpd.GeoDataFrame(
|
|
257
|
+
self.geography(geo, proj=proj).merge(
|
|
258
|
+
left_on="GEOID",
|
|
259
|
+
right_on="geo",
|
|
260
|
+
right=data_df.iloc[:, [1, 2]],
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def geography(
|
|
265
|
+
self,
|
|
266
|
+
geo: GeoSelection | GeoGroup | GeoAggregation,
|
|
267
|
+
*,
|
|
268
|
+
proj: CRS | str | None = None,
|
|
269
|
+
) -> gpd.GeoDataFrame:
|
|
270
|
+
"""
|
|
271
|
+
Calculate the geo dataframe by applying the given geo axis strategy,
|
|
272
|
+
but without merging any simulation data.
|
|
273
|
+
|
|
274
|
+
This is an advanced method that allows you to leverage the geo-handling logic
|
|
275
|
+
of `MapRenderer` without necessarily drawing a map.
|
|
276
|
+
|
|
277
|
+
Parameters
|
|
278
|
+
----------
|
|
279
|
+
geo :
|
|
280
|
+
The geographic selection to make on the source geography.
|
|
281
|
+
proj :
|
|
282
|
+
The projection to use for mapping; if `None` (default) we will
|
|
283
|
+
map using the default projection for the source geography.
|
|
284
|
+
(For US Census, this is NAD83 [https://epsg.org/crs_4269/index.html](https://epsg.org/crs_4269/index.html))
|
|
285
|
+
|
|
286
|
+
Returns
|
|
287
|
+
-------
|
|
288
|
+
:
|
|
289
|
+
The geo dataframe as a result of applying the geo axis strategies to the
|
|
290
|
+
source geography.
|
|
291
|
+
|
|
292
|
+
Raises
|
|
293
|
+
------
|
|
294
|
+
GeographyError
|
|
295
|
+
If we cannot fetch geography for the type of scope used.
|
|
296
|
+
"""
|
|
297
|
+
try:
|
|
298
|
+
gdf = geo.to_scope().geography
|
|
299
|
+
except GeographyError as e:
|
|
300
|
+
err = f"Cannot draw choropleth map: {e}"
|
|
301
|
+
raise GeographyError(err) from e
|
|
302
|
+
|
|
303
|
+
# If we have internal point info in the gdf, make it a centroid column.
|
|
304
|
+
cols = gdf.columns
|
|
305
|
+
if "INTPTLON" in cols and "INTPTLAT" in cols:
|
|
306
|
+
centroids = gpd.points_from_xy(
|
|
307
|
+
gdf["INTPTLON"],
|
|
308
|
+
gdf["INTPTLAT"],
|
|
309
|
+
crs=gdf.crs,
|
|
310
|
+
)
|
|
311
|
+
if proj is not None:
|
|
312
|
+
centroids = centroids.to_crs(proj)
|
|
313
|
+
gdf["centroid"] = centroids
|
|
314
|
+
|
|
315
|
+
return cast(gpd.GeoDataFrame, gdf if proj is None else gdf.to_crs(proj))
|
|
316
|
+
|
|
317
|
+
def choropleth(
|
|
318
|
+
self,
|
|
319
|
+
geo: GeoSelection | GeoAggregation,
|
|
320
|
+
time: TimeSelection | TimeAggregation,
|
|
321
|
+
quantity: QuantitySelection | QuantityAggregation,
|
|
322
|
+
*,
|
|
323
|
+
borders: GeoSelection | GeoGroup | None = None,
|
|
324
|
+
cmap: Any | None = None,
|
|
325
|
+
proj: CRS | str | None = None,
|
|
326
|
+
text_label: bool | str | NodeLabelRenderer = False,
|
|
327
|
+
title: str | None = None,
|
|
328
|
+
transform: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
|
|
329
|
+
vmax: float | None = None,
|
|
330
|
+
vmin: float | None = None,
|
|
331
|
+
) -> None:
|
|
332
|
+
"""
|
|
333
|
+
Render a choropleth map using GeoPandas and matplotlib showing the given
|
|
334
|
+
selections.
|
|
335
|
+
|
|
336
|
+
Selections must be made carefully to produce a valid map: the geo
|
|
337
|
+
selection and grouping will dictate which polygons are shown on the map, the
|
|
338
|
+
time selection must collapse to a single time-point, and the quantity selection
|
|
339
|
+
must collapse to a single value per node. Of course there are many ways
|
|
340
|
+
to trim the output data to that form, but we will check the result of the
|
|
341
|
+
selections to verify it during rendering, and invalid selections will result
|
|
342
|
+
in an raised exception.
|
|
343
|
+
|
|
344
|
+
The plot will be immediately rendered by this function by calling `plt.show()`.
|
|
345
|
+
This is intended as a quick plotting method to cover most casual use-cases.
|
|
346
|
+
If you want more control over how the plot is drawn, see method
|
|
347
|
+
`choropleth_plt()`.
|
|
348
|
+
|
|
349
|
+
Parameters
|
|
350
|
+
----------
|
|
351
|
+
geo :
|
|
352
|
+
The geographic selection to make on the output data.
|
|
353
|
+
time :
|
|
354
|
+
The time selection to make on the output data.
|
|
355
|
+
quantity :
|
|
356
|
+
The quantity selection to make on the output data.
|
|
357
|
+
borders :
|
|
358
|
+
If given, use this geography to draw dark borders,
|
|
359
|
+
this could be the same or different geography from `geo`;
|
|
360
|
+
if `None` (default), no borders are drawn.
|
|
361
|
+
cmap
|
|
362
|
+
The color map to use for the plot; you can pass any value
|
|
363
|
+
you would normally pass to [`geopandas.GeoDataFrame.plot`][].
|
|
364
|
+
proj :
|
|
365
|
+
The projection to use for mapping; if `None` (default) we will
|
|
366
|
+
map using the default projection for the source geography.
|
|
367
|
+
(For US Census, this is NAD83 [https://epsg.org/crs_4269/index.html](https://epsg.org/crs_4269/index.html))
|
|
368
|
+
text_label :
|
|
369
|
+
True to render a text label of the data value for each polygon in white;
|
|
370
|
+
a string to specify a different color, or a `NodeLabelRenderer` instance
|
|
371
|
+
to use that.
|
|
372
|
+
title :
|
|
373
|
+
A title to draw on the plot.
|
|
374
|
+
transform :
|
|
375
|
+
Allows you to specify an arbitrary transform function on the source
|
|
376
|
+
dataframe before we plot it, e.g., to rescale the values.
|
|
377
|
+
The dataframe given as the argument is the result of applying
|
|
378
|
+
all selections and the projection if specified.
|
|
379
|
+
You should return a dataframe with the same format, where the
|
|
380
|
+
data column has been modified for your purposes.
|
|
381
|
+
|
|
382
|
+
Dataframe columns:
|
|
383
|
+
- "geo": the node ID of each polygon
|
|
384
|
+
- "data": the data value from the quantity selection
|
|
385
|
+
vmax :
|
|
386
|
+
The max value for the color map, by default the max value of the data.
|
|
387
|
+
vmin :
|
|
388
|
+
The min value for the color map, by default the min value of the data.
|
|
389
|
+
|
|
390
|
+
Raises
|
|
391
|
+
------
|
|
392
|
+
GeographyError
|
|
393
|
+
If we cannot fetch geography for the type of scope used.
|
|
394
|
+
"""
|
|
395
|
+
try:
|
|
396
|
+
fig, ax = plt.subplots(layout="constrained")
|
|
397
|
+
ax.axis("off")
|
|
398
|
+
|
|
399
|
+
data_gdf, color_scale = self.choropleth_plt(
|
|
400
|
+
ax,
|
|
401
|
+
geo,
|
|
402
|
+
time,
|
|
403
|
+
quantity,
|
|
404
|
+
borders=borders,
|
|
405
|
+
cmap=cmap,
|
|
406
|
+
proj=proj,
|
|
407
|
+
transform=transform,
|
|
408
|
+
vmax=vmax,
|
|
409
|
+
vmin=vmin,
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
# Draw colorbar
|
|
413
|
+
fig.colorbar(mappable=color_scale, ax=ax, format=EngFormatter(sep=""))
|
|
414
|
+
|
|
415
|
+
# Draw text labels on each polygon?
|
|
416
|
+
if text_label is not False:
|
|
417
|
+
if isinstance(text_label, str):
|
|
418
|
+
labeler = NodeLabelRenderer(text_label)
|
|
419
|
+
elif isinstance(text_label, NodeLabelRenderer):
|
|
420
|
+
labeler = text_label
|
|
421
|
+
else:
|
|
422
|
+
labeler = NodeLabelRenderer()
|
|
423
|
+
labeler.render(ax, data_gdf, color_scale)
|
|
424
|
+
|
|
425
|
+
if title is not None:
|
|
426
|
+
plt.title(title)
|
|
427
|
+
|
|
428
|
+
plt.show()
|
|
429
|
+
except:
|
|
430
|
+
plt.close()
|
|
431
|
+
raise
|
|
432
|
+
|
|
433
|
+
def choropleth_plt(
|
|
434
|
+
self,
|
|
435
|
+
ax: Axes,
|
|
436
|
+
geo: GeoSelection | GeoAggregation,
|
|
437
|
+
time: TimeSelection | TimeAggregation,
|
|
438
|
+
quantity: QuantitySelection | QuantityAggregation,
|
|
439
|
+
*,
|
|
440
|
+
borders: GeoSelection | GeoGroup | None = None,
|
|
441
|
+
cmap: Any | None = None,
|
|
442
|
+
proj: CRS | str | None = None,
|
|
443
|
+
transform: Callable[[pd.DataFrame], pd.DataFrame] | None = None,
|
|
444
|
+
vmax: float | None = None,
|
|
445
|
+
vmin: float | None = None,
|
|
446
|
+
) -> tuple[gpd.GeoDataFrame, ScalarMappable]:
|
|
447
|
+
"""
|
|
448
|
+
Draw a choropleth map onto the given matplotlib axes showing the given
|
|
449
|
+
selections. This is a variant of the method `choropleth()` that gives you
|
|
450
|
+
more control over the rendering of a plot by letting you do most of the work
|
|
451
|
+
with matplotlib's API. See that method for conditions that must be met to use
|
|
452
|
+
this method effectively.
|
|
453
|
+
|
|
454
|
+
Parameters
|
|
455
|
+
----------
|
|
456
|
+
ax :
|
|
457
|
+
The plot axes on which to draw the map.
|
|
458
|
+
geo :
|
|
459
|
+
The geographic selection to make on the output data.
|
|
460
|
+
time :
|
|
461
|
+
The time selection to make on the output data.
|
|
462
|
+
quantity :
|
|
463
|
+
The quantity selection to make on the output data.
|
|
464
|
+
borders :
|
|
465
|
+
If given, use this geography to draw dark borders,
|
|
466
|
+
this could be the same or different geography from `geo`;
|
|
467
|
+
if `None` (default), no borders are drawn.
|
|
468
|
+
cmap :
|
|
469
|
+
The color map to use for the plot; you can pass any value
|
|
470
|
+
you would normally pass to [`geopandas.GeoDataFrame.plot`][].
|
|
471
|
+
proj :
|
|
472
|
+
The projection to use for mapping; if `None` (default) we will
|
|
473
|
+
map using the default projection for the source geography.
|
|
474
|
+
(For US Census, this is NAD83 [https://epsg.org/crs_4269/index.html](https://epsg.org/crs_4269/index.html))
|
|
475
|
+
transform :
|
|
476
|
+
Allows you to specify an arbitrary transform function on the source
|
|
477
|
+
dataframe before we plot it, e.g., to rescale the values.
|
|
478
|
+
The dataframe given as the argument is the result of applying
|
|
479
|
+
all selections and the projection if specified.
|
|
480
|
+
You should return a dataframe with the same format, where the
|
|
481
|
+
data column has been modified for your purposes.
|
|
482
|
+
|
|
483
|
+
Dataframe columns:
|
|
484
|
+
- "geo": the node ID of each polygon
|
|
485
|
+
- "data": the data value from the quantity selection
|
|
486
|
+
vmax :
|
|
487
|
+
The max value for the color map, by default the max value of the data.
|
|
488
|
+
vmin :
|
|
489
|
+
The min value for the color map, by default the min value of the data.
|
|
490
|
+
|
|
491
|
+
Returns
|
|
492
|
+
-------
|
|
493
|
+
:
|
|
494
|
+
a tuple with 1. the geo dataframe containing the data used to render the map
|
|
495
|
+
and 2. the map's color scale.
|
|
496
|
+
|
|
497
|
+
Raises
|
|
498
|
+
------
|
|
499
|
+
GeographyError
|
|
500
|
+
If we cannot fetch geography for the type of scope used.
|
|
501
|
+
"""
|
|
502
|
+
data_gdf = self.geography_data(
|
|
503
|
+
geo,
|
|
504
|
+
time,
|
|
505
|
+
quantity,
|
|
506
|
+
proj=proj,
|
|
507
|
+
transform=transform,
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
vmin = vmin if vmin is not None else cast(float, data_gdf["data"].min()) # type: ignore
|
|
511
|
+
vmax = vmax if vmax is not None else cast(float, data_gdf["data"].max()) # type: ignore
|
|
512
|
+
color_scale = plt.cm.ScalarMappable(
|
|
513
|
+
cmap=cmap,
|
|
514
|
+
norm=Normalize(vmin, vmax),
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
# Draw polygons.
|
|
518
|
+
data_gdf.plot(
|
|
519
|
+
ax=ax,
|
|
520
|
+
column="data",
|
|
521
|
+
legend=False,
|
|
522
|
+
cmap=color_scale.cmap,
|
|
523
|
+
vmin=color_scale.norm.vmin,
|
|
524
|
+
vmax=color_scale.norm.vmax,
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
# Draw borders?
|
|
528
|
+
if borders is not None:
|
|
529
|
+
borders_gdf = self.geography(borders, proj=proj)
|
|
530
|
+
borders_gdf.plot(
|
|
531
|
+
ax=ax,
|
|
532
|
+
linewidth=1,
|
|
533
|
+
edgecolor="black",
|
|
534
|
+
color="none",
|
|
535
|
+
alpha=0.8,
|
|
536
|
+
legend=False,
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
return data_gdf, color_scale
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
class MapRendererMixin(Output):
|
|
543
|
+
"""
|
|
544
|
+
Mixin class that adds a convenient method for rendering choropleth maps from an
|
|
545
|
+
output.
|
|
546
|
+
"""
|
|
547
|
+
|
|
548
|
+
@property
|
|
549
|
+
def map(self) -> MapRenderer:
|
|
550
|
+
"""Render a choropleth map from this output."""
|
|
551
|
+
return MapRenderer(self)
|