-
Notifications
You must be signed in to change notification settings - Fork 457
Expand file tree
/
Copy pathplotting.py
More file actions
318 lines (285 loc) · 11.5 KB
/
Copy pathplotting.py
File metadata and controls
318 lines (285 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
from pathlib import Path
import colorsys
from dataclasses import dataclass, field
from geopandas import GeoDataFrame
import numpy as np
from matplotlib.collections import LineCollection, PatchCollection
from matplotlib.colors import ListedColormap, cnames, to_rgb
from matplotlib.path import Path as MplPath
from matplotlib.pyplot import subplots, Rectangle
import matplotlib.font_manager as fm
from matplotlib.patches import Ellipse, PathPatch
import matplotlib.patheffects as PathEffects
from prettymapp.settings import STREETS_WIDTH, STYLES
def plot_polygon_collection(
ax, geoms, values=None, cmap=None, **kwargs
) -> PatchCollection:
"""
Plot shapely Polygons as a single matplotlib PatchCollection (honors holes).
Faster than geodataframe.plot() as it does not use plt.draw(), the figure is
rendered only once e.g. in st.pyplot.
"""
patches = [
PathPatch(
MplPath.make_compound_path(
MplPath(np.asarray(poly.exterior.coords)[:, :2]),
*[MplPath(np.asarray(ring.coords)[:, :2]) for ring in poly.interiors],
)
)
for poly in geoms
]
collection = PatchCollection(patches, cmap=cmap, **kwargs)
if values is not None:
collection.set_array(np.asarray(values))
ax.add_collection(collection, autolim=True)
return collection
def plot_linestring_collection(ax, geoms, **kwargs) -> LineCollection:
"""
Plot shapely LineStrings as a single matplotlib LineCollection.
"""
collection = LineCollection(
[np.asarray(line.coords)[:, :2] for line in geoms], **kwargs
)
ax.add_collection(collection, autolim=True)
return collection
@dataclass
class Plot:
"""
Main plotting class for prettymapp.
Args:
df: GeoDataFrame with the geometries to plot
aoi_bounds: List of minx, miny, maxx, maxy coordinates, specifying the map extent
draw_settings: Dictionary of color & draw settings, see prettymapp.settings.STYLES
# Map layout
shape: the map shape, "circle" or "rectangle"
contour_width: width of the map contour, defaults to 0
contour_color: color of the map contour, defaults to "#2F3537"
# Optional map text settings e.g. to display location name
name_on: whether to display the location name, defaults to False
name: the location name to display, defaults to "some name"
font_size: font size of the location name, defaults to 25
font_color: color of the location name, defaults to "#2F3737"
text_x: x-coordinate of the location name, defaults to 0
text_y: y-coordinate of the location name, defaults to 0
text_rotation: rotation of the location name, defaults to 0
credits: Boolean whether to display the OSM&package credits, defaults to True
# Map background settings
bg_shape: the map background shape, "circle" or "rectangle", defaults to "rectangle"
bg_buffer: buffer around the map, defaults to 2
bg_color: color of the map background, defaults to "#F2F4CB"
# Figure settings
dpi: figure resolution in dots per inch, defaults to 300
"""
df: GeoDataFrame
aoi_bounds: list[
float
] # Not df bounds as could lead to weird plot shapes with unequal geometry distribution.
draw_settings: dict = field(default_factory=lambda: STYLES["Peach"])
# Map layout settings
shape: str = "circle"
contour_width: int = 0
contour_color: str = "#2F3537"
# Optional map text settings e.g. to display location name
name_on: bool = False
name: str = "some name"
font_size: int = 25
font_color: str = "#2F3737"
text_x: int = 0
text_y: int = 0
text_rotation: int = 0
credits: bool = True
# Map background settings
bg_shape: str = "rectangle"
bg_buffer: int = 2
bg_color: str = "#F2F4CB"
# Figure settings
dpi: int = 300
def __post_init__(self):
(
self.xmin,
self.ymin,
self.xmax,
self.ymax,
) = self.aoi_bounds
# take from aoi geometry bounds, otherwise probelematic if unequal geometry distribution over plot.
self.xmid = (self.xmin + self.xmax) / 2
self.ymid = (self.ymin + self.ymax) / 2
self.xdif = self.xmax - self.xmin
self.ydif = self.ymax - self.ymin
self.bg_buffer_x = (self.bg_buffer / 100) * self.xdif
self.bg_buffer_y = (self.bg_buffer / 100) * self.ydif
self.fig, self.ax = subplots(
1, 1, figsize=(12, 12), constrained_layout=True, dpi=self.dpi
)
self.ax.set_aspect(1 / np.cos(self.ymid * np.pi / 180))
self.ax.axis("off")
self.ax.set_xlim(self.xmin - self.bg_buffer_x, self.xmax + self.bg_buffer_x)
self.ax.set_ylim(self.ymin - self.bg_buffer_y, self.ymax + self.bg_buffer_y)
def plot_all(self):
if self.bg_shape is not None:
self.set_background()
self.set_geometries()
if self.contour_width:
self.set_map_contour()
if self.name_on:
self.set_name()
if self.credits:
self.set_credits()
return self.fig
def set_geometries(self):
"""
Avoids using geodataframe.plot() as this uses plt.draw(), but for the app, the figure needs to be rendered
only in st.pyplot. Shaves off 1 sec.
"""
# Seeded rng so identical inputs render identical (reproducible) maps.
rng = np.random.default_rng(42)
for lc_class in self.df["landcover_class"].unique():
df_class = self.df[self.df["landcover_class"] == lc_class]
try:
draw_settings_class = self.draw_settings[lc_class].copy()
except KeyError:
continue
# pylint: disable=no-else-continue
if lc_class == "streets":
df_class = df_class[df_class.geom_type == "LineString"]
linewidth_values = list(
df_class["highway"].map(STREETS_WIDTH).fillna(1)
)
draw_settings_class["ec"] = draw_settings_class.pop("fc")
linecollection = plot_linestring_collection(
ax=self.ax, geoms=df_class.geometry, **draw_settings_class
)
linecollection.set_linewidth(linewidth_values)
continue
else:
df_class = df_class[df_class.geom_type == "Polygon"]
if "hatch_c" in draw_settings_class:
# Matplotlib hatch color is set via ec. hatch_c is used as the edge color here by plotting the outlines
# again above.
plot_polygon_collection(
ax=self.ax,
geoms=df_class.geometry,
fc="None",
ec=draw_settings_class["hatch_c"],
lw=1,
zorder=6,
)
draw_settings_class.pop("hatch_c")
if "cmap" in draw_settings_class:
cmap_colors = draw_settings_class.pop("cmap")
cmap_values = rng.integers(0, len(cmap_colors), df_class.shape[0])
plot_polygon_collection(
ax=self.ax,
geoms=df_class.geometry,
values=cmap_values,
cmap=ListedColormap(cmap_colors),
**draw_settings_class,
)
else:
plot_polygon_collection(
ax=self.ax, geoms=df_class.geometry, **draw_settings_class
)
def set_map_contour(self):
if self.shape == "rectangle":
patch = Rectangle(
xy=(self.xmin, self.ymin),
width=self.xdif,
height=self.ydif,
color="None",
lw=self.contour_width,
ec=self.contour_color,
zorder=6,
clip_on=True,
)
self.ax.add_patch(patch)
elif self.shape == "circle":
# axis aspect ratio no equal so ellipse required to display as circle
ellipse = Ellipse(
xy=(self.xmid, self.ymid), # centroid
width=self.xdif,
height=self.ydif,
color="None",
lw=self.contour_width,
ec=self.contour_color,
zorder=6,
clip_on=True,
)
self.ax.add_artist(ellipse)
# re-enable patch for background color that is deactivated with axis
self.ax.patch.set_zorder(6)
def set_background(self):
ec = adjust_lightness(self.bg_color, 0.78)
if self.bg_shape == "rectangle":
patch = Rectangle(
xy=(self.xmin - self.bg_buffer_x, self.ymin - self.bg_buffer_y),
width=self.xdif + 2 * self.bg_buffer_x,
height=self.ydif + 2 * self.bg_buffer_y,
color=self.bg_color,
ec=ec,
hatch="ooo...",
zorder=-1,
clip_on=True,
)
self.ax.add_patch(patch)
elif self.bg_shape == "circle":
# axis aspect ratio no equal so ellipse required to display as circle
ellipse = Ellipse(
xy=(self.xmid, self.ymid), # centroid
width=self.xdif + 2 * self.bg_buffer_x,
height=self.ydif + 2 * self.bg_buffer_y,
facecolor=self.bg_color,
ec=adjust_lightness(self.bg_color, 0.78),
hatch="ooo...",
zorder=-1,
clip_on=True,
)
self.ax.add_artist(ellipse)
# re-enable patch for background color that is deactivated with axis
self.ax.patch.set_zorder(-1)
def set_name(self):
x = self.xmid + self.text_x / 100 * self.xdif
y = self.ymid + self.text_y / 100 * self.ydif
_location_ = Path(__file__).resolve().parent
fpath = _location_ / "fonts/PermanentMarker-Regular.ttf"
fontproperties = fm.FontProperties(fname=fpath.resolve())
self.ax.text(
x=x,
y=y,
s=self.name,
color=self.font_color,
zorder=6,
ha="center",
rotation=self.text_rotation * -1,
fontproperties=fontproperties,
size=self.font_size,
)
def set_credits(
self,
text: str = "© OpenStreetMap\n prettymapp | prettymaps",
x: float | None = None,
y: float | None = None,
fontsize: int = 9,
zorder: int = 6,
):
"""
Add OSM credits. Defaults to lower right corner of map.
"""
if x is None:
x = self.xmin + 0.87 * self.xdif
if y is None:
y = self.ymin - 0.70 * self.bg_buffer_y
text = self.ax.text(x=x, y=y, s=text, c="w", fontsize=fontsize, zorder=zorder)
text.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="black")])
def adjust_lightness(color: str, amount: float = 0.5) -> tuple[float, float, float]:
"""
In-/Decrease color brightness amount by factor.
Helper to avoid having the user define background ec color value which is similar to background color.
via https://stackoverflow.com/questions/37765197/darken-or-lighten-a-color-in-matplotlib
"""
try:
c = cnames[color]
except KeyError:
c = color
c = colorsys.rgb_to_hls(*to_rgb(c))
adjusted_c = colorsys.hls_to_rgb(c[0], max(0, min(1, amount * c[1])), c[2])
return adjusted_c