Skip to content

API Reference

This section is auto-generated from the Prettymaps source code.

prettymaps.draw

Prettymaps - A minimal Python library to draw pretty maps from OpenStreetMap Data Copyright (C) 2021 Marcelo Prates

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/.

Plot dataclass

Dataclass implementing a prettymaps Plot object.

Attributes:

Name Type Description
geodataframes Dict[str, GeoDataFrame]

A dictionary of GeoDataFrames (one for each plot layer).

fig Figure

A matplotlib figure.

ax Axes

A matplotlib axis object.

background BaseGeometry

Background layer (shapely object).

keypoints GeoDataFrame

Keypoints GeoDataFrame.

Source code in prettymaps/draw.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass
class Plot:
    """
    Dataclass implementing a prettymaps Plot object.

    Attributes:
        geodataframes (Dict[str, gp.GeoDataFrame]): A dictionary of GeoDataFrames (one for each plot layer).
        fig (matplotlib.figure.Figure): A matplotlib figure.
        ax (matplotlib.axes.Axes): A matplotlib axis object.
        background (BaseGeometry): Background layer (shapely object).
        keypoints (gp.GeoDataFrame): Keypoints GeoDataFrame.
    """

    geodataframes: Dict[str, gp.GeoDataFrame]
    fig: matplotlib.figure.Figure
    ax: matplotlib.axes.Axes
    background: BaseGeometry
    keypoints: gp.GeoDataFrame

PolygonPatch

Bases: PathPatch

A class to create a matplotlib PathPatch from a shapely geometry.

Attributes:

Name Type Description
shape BaseGeometry

Shapely geometry.

kwargs BaseGeometry

Parameters for matplotlib's PathPatch constructor.

Methods:

Name Description
__init__

BaseGeometry, **kwargs): Initialize the PolygonPatch with the given shapely geometry and additional parameters.

shape (BaseGeometry): Shapely geometry. kwargs: Parameters for matplotlib's PathPatch constructor.

Source code in prettymaps/draw.py
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
class PolygonPatch(PathPatch):
    """
    A class to create a matplotlib PathPatch from a shapely geometry.

    Attributes:
        shape (BaseGeometry): Shapely geometry.
        kwargs: Parameters for matplotlib's PathPatch constructor.

    Methods:
        __init__(shape: BaseGeometry, **kwargs):
            Initialize the PolygonPatch with the given shapely geometry and additional parameters.


            shape (BaseGeometry): Shapely geometry.
            kwargs: Parameters for matplotlib's PathPatch constructor.
    """

    def __init__(self, shape: BaseGeometry, **kwargs):
        """
        Initialize the PolygonPatch.

        Args:
            shape (BaseGeometry): Shapely geometry
            kwargs: parameters for matplotlib's PathPatch constructor
        """
        # Init vertices and codes lists
        vertices, codes = [], []
        for geom in shape.geoms if hasattr(shape, "geoms") else [shape]:
            for poly in geom.geoms if hasattr(geom, "geoms") else [geom]:
                if type(poly) != Polygon:
                    continue
                # Get polygon's exterior and interiors
                exterior = np.array(poly.exterior.xy)
                interiors = [np.array(interior.xy) for interior in poly.interiors]
                # Append to vertices and codes lists
                vertices += [exterior] + interiors
                codes += list(
                    map(
                        # Ring coding
                        lambda p: [Path.MOVETO]
                        + [Path.LINETO] * (p.shape[1] - 2)
                        + [Path.CLOSEPOLY],
                        [exterior] + interiors,
                    )
                )
        # Initialize PathPatch with the generated Path
        super().__init__(
            Path(np.concatenate(vertices, 1).T, np.concatenate(codes)), **kwargs
        )

__init__(shape, **kwargs)

Initialize the PolygonPatch.

Parameters:

Name Type Description Default
shape BaseGeometry

Shapely geometry

required
kwargs

parameters for matplotlib's PathPatch constructor

{}
Source code in prettymaps/draw.py
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
def __init__(self, shape: BaseGeometry, **kwargs):
    """
    Initialize the PolygonPatch.

    Args:
        shape (BaseGeometry): Shapely geometry
        kwargs: parameters for matplotlib's PathPatch constructor
    """
    # Init vertices and codes lists
    vertices, codes = [], []
    for geom in shape.geoms if hasattr(shape, "geoms") else [shape]:
        for poly in geom.geoms if hasattr(geom, "geoms") else [geom]:
            if type(poly) != Polygon:
                continue
            # Get polygon's exterior and interiors
            exterior = np.array(poly.exterior.xy)
            interiors = [np.array(interior.xy) for interior in poly.interiors]
            # Append to vertices and codes lists
            vertices += [exterior] + interiors
            codes += list(
                map(
                    # Ring coding
                    lambda p: [Path.MOVETO]
                    + [Path.LINETO] * (p.shape[1] - 2)
                    + [Path.CLOSEPOLY],
                    [exterior] + interiors,
                )
            )
    # Initialize PathPatch with the generated Path
    super().__init__(
        Path(np.concatenate(vertices, 1).T, np.concatenate(codes)), **kwargs
    )

Preset dataclass

Dataclass implementing a prettymaps Preset object.

Attributes:

Name Type Description
params dict

Dictionary of prettymaps.plot() parameters.

Source code in prettymaps/draw.py
103
104
105
106
107
108
109
110
111
112
@dataclass
class Preset:
    """
    Dataclass implementing a prettymaps Preset object.

    Attributes:
        params (dict): Dictionary of prettymaps.plot() parameters.
    """

    params: dict

Subplot

Class implementing a prettymaps Subplot. Attributes: - query: prettymaps.plot() query - kwargs: dictionary of prettymaps.plot() parameters

Source code in prettymaps/draw.py
71
72
73
74
75
76
77
78
79
80
class Subplot:
    """
    Class implementing a prettymaps Subplot. Attributes:
    - query: prettymaps.plot() query
    - kwargs: dictionary of prettymaps.plot() parameters
    """

    def __init__(self, query, **kwargs):
        self.query = query
        self.kwargs = kwargs

create_background(gdfs, style, logging=False)

Create a background layer given a collection of GeoDataFrames

Parameters:

Name Type Description Default
gdfs Dict[str, GeoDataFrame]

Dictionary of GeoDataFrames

required
style Dict[str, dict]

Dictionary of matplotlib style parameters

required

Returns:

Type Description
Tuple[BaseGeometry, float, float, float, float, float, float]

Tuple[BaseGeometry, float, float, float, float, float, float]: background geometry, bounds, width and height

Source code in prettymaps/draw.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
@log_execution_time
def create_background(
    gdfs: Dict[str, gp.GeoDataFrame],
    style: Dict[str, dict],
    logging=False,
) -> Tuple[BaseGeometry, float, float, float, float, float, float]:
    """
    Create a background layer given a collection of GeoDataFrames

    Args:
        gdfs (Dict[str, gp.GeoDataFrame]): Dictionary of GeoDataFrames
        style (Dict[str, dict]): Dictionary of matplotlib style parameters

    Returns:
        Tuple[BaseGeometry, float, float, float, float, float, float]: background geometry, bounds, width and height
    """

    # Create background
    background_pad = 1.1
    if "background" in style and "pad" in style["background"]:
        background_pad = style["background"].pop("pad")

    background = shapely.affinity.scale(
        box(
            *shapely.ops.unary_union(ox.project_gdf(gdfs["perimeter"]).geometry).bounds
        ),
        background_pad,
        background_pad,
    )

    if "background" in style and "dilate" in style["background"]:
        background = background.buffer(style["background"].pop("dilate"))

    # Get bounds
    xmin, ymin, xmax, ymax = background.bounds
    dx, dy = xmax - xmin, ymax - ymin

    return background, xmin, ymin, xmax, ymax, dx, dy

create_preset(name, layers=None, style=None, circle=None, radius=None, dilate=None)

Create a preset file and save it on the presets folder (prettymaps/presets/) under name 'name.json'

Parameters:

Name Type Description Default
name str

Preset name

required
layers Dict[str, dict]

prettymaps.plot() 'layers' parameter dict. Defaults to None.

None
style Dict[str, dict]

prettymaps.plot() 'style' parameter dict. Defaults to None.

None
circle Optional[bool]

prettymaps.plot() 'circle' parameter. Defaults to None.

None
radius Optional[Union[float, bool]]

prettymaps.plot() 'radius' parameter. Defaults to None.

None
dilate Optional[Union[float, bool]]

prettymaps.plot() 'dilate' parameter. Defaults to None.

None
Source code in prettymaps/draw.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
def create_preset(
    name: str,
    layers: Optional[Dict[str, dict]] = None,
    style: Optional[Dict[str, dict]] = None,
    circle: Optional[bool] = None,
    radius: Optional[Union[float, bool]] = None,
    dilate: Optional[Union[float, bool]] = None,
) -> None:
    """
    Create a preset file and save it on the presets folder (prettymaps/presets/) under name 'name.json'

    Args:
        name (str): Preset name
        layers (Dict[str, dict], optional): prettymaps.plot() 'layers' parameter dict. Defaults to None.
        style (Dict[str, dict], optional): prettymaps.plot() 'style' parameter dict. Defaults to None.
        circle (Optional[bool], optional): prettymaps.plot() 'circle' parameter. Defaults to None.
        radius (Optional[Union[float, bool]], optional): prettymaps.plot() 'radius' parameter. Defaults to None.
        dilate (Optional[Union[float, bool]], optional): prettymaps.plot() 'dilate' parameter. Defaults to None.
    """

    # if not os.path.isdir('presets'):
    #    os.makedirs('presets')

    path = os.path.join(presets_directory(), f"{name}.json")
    with open(path, "w") as f:
        json.dump(
            {
                "layers": layers,
                "style": style,
                "circle": circle,
                "radius": radius,
                "dilate": dilate,
            },
            f,
            ensure_ascii=False,
        )

draw_credit(ax, background, credit, mode, multiplot, logging=False)

Draws credit text on the plot.

Parameters:

Name Type Description Default
ax Axes

Matplotlib axis object.

required
background BaseGeometry

Background layer.

required
credit Dict[str, Any]

Dictionary containing credit text and style parameters.

required
mode str

Drawing mode. Options: 'matplotlib', 'plotter'.

required
multiplot bool

Whether the plot is part of a multiplot.

required
logging bool

Whether to enable logging. Defaults to False.

False
Source code in prettymaps/draw.py
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
@log_execution_time
def draw_credit(
    ax: matplotlib.axes.Axes,
    background: BaseGeometry,
    credit: Dict[str, Any],
    mode: str,
    multiplot: bool,
    logging: bool = False,
) -> None:
    """
    Draws credit text on the plot.

    Args:
        ax (matplotlib.axes.Axes): Matplotlib axis object.
        background (BaseGeometry): Background layer.
        credit (Dict[str, Any]): Dictionary containing credit text and style parameters.
        mode (str): Drawing mode. Options: 'matplotlib', 'plotter'.
        multiplot (bool): Whether the plot is part of a multiplot.
        logging (bool, optional): Whether to enable logging. Defaults to False.
    """
    if (mode == "matplotlib") and (credit != False) and (not multiplot):
        draw_text(ax, credit, background)

draw_text(ax, params, background)

Draw text with content and matplotlib style parameters specified by 'params' dictionary. params['text'] should contain the message to be drawn.

Parameters:

Name Type Description Default
ax Axes

Matplotlib axis object.

required
params Dict[str, Any]

Matplotlib style parameters for drawing text. params['text'] should contain the message to be drawn.

required
background BaseGeometry

Background layer.

required
Source code in prettymaps/draw.py
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
def draw_text(
    ax: matplotlib.axes.Axes, params: Dict[str, Any], background: BaseGeometry
) -> None:
    """
    Draw text with content and matplotlib style parameters specified by 'params' dictionary.
    params['text'] should contain the message to be drawn.

    Args:
        ax (matplotlib.axes.Axes): Matplotlib axis object.
        params (Dict[str, Any]): Matplotlib style parameters for drawing text. params['text'] should contain the message to be drawn.
        background (BaseGeometry): Background layer.
    """
    # Override default osm_credit dict with provided parameters
    params = override_params(
        dict(
            text="\n".join(
                [
                    "data © OpenStreetMap contributors",
                    "github.com/marceloprates/prettymaps",
                ]
            ),
            x=0,
            y=1,
            horizontalalignment="left",
            verticalalignment="top",
            bbox=dict(boxstyle="square", fc="#fff", ec="#000"),
            # fontfamily="Ubuntu Mono",
        ),
        params,
    )
    x, y, text = [params.pop(k) for k in ["x", "y", "text"]]

    # Get background bounds
    xmin, ymin, xmax, ymax = background.bounds

    x = np.interp([x], [0, 1], [xmin, xmax])[0]
    y = np.interp([y], [0, 1], [ymin, ymax])[0]

    ax.text(x, y, text, zorder=1000, **params)

gdf_to_shapely(layer, gdf, width=None, point_size=None, line_width=None, **kwargs)

Convert a dict of GeoDataFrames to a dict of shapely geometries

Parameters:

Name Type Description Default
layer str

Layer name

required
gdf GeoDataFrame

Input GeoDataFrame

required
width Optional[Union[dict, float]]

Street network width. Can be either a dictionary or a float. Defaults to None.

None
point_size Optional[float]

Point geometries (1D) will be dilated by this amount. Defaults to None.

None
line_width Optional[float]

Line geometries (2D) will be dilated by this amount. Defaults to None.

None

Returns:

Name Type Description
GeometryCollection GeometryCollection

Output GeoDataFrame

Source code in prettymaps/draw.py
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
def gdf_to_shapely(
    layer: str,
    gdf: gp.GeoDataFrame,
    width: Optional[Union[dict, float]] = None,
    point_size: Optional[float] = None,
    line_width: Optional[float] = None,
    **kwargs,
) -> GeometryCollection:
    """
    Convert a dict of GeoDataFrames to a dict of shapely geometries

    Args:
        layer (str): Layer name
        gdf (gp.GeoDataFrame): Input GeoDataFrame
        width (Optional[Union[dict, float]], optional): Street network width. Can be either a dictionary or a float. Defaults to None.
        point_size (Optional[float], optional): Point geometries (1D) will be dilated by this amount. Defaults to None.
        line_width (Optional[float], optional): Line geometries (2D) will be dilated by this amount. Defaults to None.

    Returns:
        GeometryCollection: Output GeoDataFrame
    """

    # Project gdf if applicable
    if not gdf.empty and gdf.crs is not None:
        gdf = ox.project_gdf(gdf)

    if layer in ["streets", "railway", "waterway"]:
        geometries = graph_to_shapely(gdf, width)
    else:
        geometries = geometries_to_shapely(
            gdf, point_size=point_size, line_width=line_width
        )

    return geometries

geometries_to_shapely(gdf, point_size=None, line_width=None)

Convert geometries in GeoDataFrame to shapely format

Parameters:

Name Type Description Default
gdf GeoDataFrame

Input GeoDataFrame

required
point_size Optional[float]

Point geometries (1D) will be dilated by this amount. Defaults to None.

None
line_width Optional[float]

Line geometries (2D) will be dilated by this amount. Defaults to None.

None

Returns:

Name Type Description
GeometryCollection GeometryCollection

Shapely geometries computed from GeoDataFrame geometries

Source code in prettymaps/draw.py
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
def geometries_to_shapely(
    gdf: gp.GeoDataFrame,
    point_size: Optional[float] = None,
    line_width: Optional[float] = None,
) -> GeometryCollection:
    """
    Convert geometries in GeoDataFrame to shapely format

    Args:
        gdf (gp.GeoDataFrame): Input GeoDataFrame
        point_size (Optional[float], optional): Point geometries (1D) will be dilated by this amount. Defaults to None.
        line_width (Optional[float], optional): Line geometries (2D) will be dilated by this amount. Defaults to None.

    Returns:
        GeometryCollection: Shapely geometries computed from GeoDataFrame geometries
    """

    geoms = gdf.geometry.tolist()
    collections = [x for x in geoms if type(x) == GeometryCollection]
    points = [x for x in geoms if type(x) == Point] + [
        y for x in collections for y in x.geoms if type(y) == Point
    ]
    lines = [x for x in geoms if type(x) in [LineString, MultiLineString]] + [
        y
        for x in collections
        for y in x.geoms
        if type(y) in [LineString, MultiLineString]
    ]
    polys = [x for x in geoms if type(x) in [Polygon, MultiPolygon]] + [
        y for x in collections for y in x.geoms if type(y) in [Polygon, MultiPolygon]
    ]

    # Convert points into circles with radius "point_size"
    if point_size:
        points = [x.buffer(point_size) for x in points] if point_size > 0 else []
    if line_width:
        lines = [x.buffer(line_width) for x in lines] if line_width > 0 else []

    return GeometryCollection(list(points) + list(lines) + list(polys))

graph_to_shapely(gdf, width=1.0)

Given a GeoDataFrame containing a graph (street newtork), convert them to shapely geometries by applying dilation given by 'width'

Parameters:

Name Type Description Default
gdf GeoDataFrame

input GeoDataFrame containing graph (street network) geometries

required
width float

Line geometries will be dilated by this amount. Defaults to 1..

1.0

Returns:

Name Type Description
BaseGeometry BaseGeometry

Shapely

Source code in prettymaps/draw.py
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
def graph_to_shapely(gdf: gp.GeoDataFrame, width: float = 1.0) -> BaseGeometry:
    """
    Given a GeoDataFrame containing a graph (street newtork),
    convert them to shapely geometries by applying dilation given by 'width'

    Args:
        gdf (gp.GeoDataFrame): input GeoDataFrame containing graph (street network) geometries
        width (float, optional): Line geometries will be dilated by this amount. Defaults to 1..

    Returns:
        BaseGeometry: Shapely
    """

    def highway_to_width(highway):
        if (type(highway) == str) and (highway in width):
            return width[highway]
        elif isinstance(highway, Iterable):
            for h in highway:
                if h in width:
                    return width[h]
            return np.nan
        else:
            return np.nan

    # Annotate GeoDataFrame with the width for each highway type
    gdf["width"] = (
        gdf["highway"].map(highway_to_width) if type(width) == dict else width
    )

    # Remove rows with inexistent width
    gdf.drop(gdf[gdf.width.isna()].index, inplace=True)

    with warnings.catch_warnings():
        # Supress shapely.errors.ShapelyDeprecationWarning
        warnings.simplefilter("ignore", shapely.errors.ShapelyDeprecationWarning)
        if not all(gdf.width.isna()):
            # Dilate geometries based on their width
            gdf.geometry = gdf.apply(
                lambda row: row["geometry"].buffer(row.width), axis=1
            )

    return shapely.ops.unary_union(gdf.geometry)

manage_presets(load_preset, save_preset, update_preset, layers, style, circle, radius, dilate, logging=False)

summary

Parameters:

Name Type Description Default
load_preset Optional[str]

Load preset named 'load_preset', if provided

required
save_preset Optional[str]

Save preset to file named 'save_preset', if provided

required
update_preset Optional[str]

Load, update and save preset named 'update_preset', if provided

required
layers Dict[str, dict]

prettymaps.plot() 'layers' parameter dict

required
style Dict[str, dict]

prettymaps.plot() 'style' parameter dict

required
circle Optional[bool]

prettymaps.plot() 'circle' parameter

required
radius Optional[Union[float, bool]]

prettymaps.plot() 'radius' parameter

required
dilate Optional[Union[float, bool]]

prettymaps.plot() 'dilate' parameter

required

Returns:

Type Description
Tuple[dict, dict, Optional[float], Optional[Union[float, bool]], Optional[Union[float, bool]]]

Tuple[dict, dict, Optional[float], Optional[Union[float, bool]], Optional[Union[float, bool]]]: Updated layers, style, circle, radius, dilate parameters

Source code in prettymaps/draw.py
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
@log_execution_time
def manage_presets(
    load_preset: Optional[str],
    save_preset: bool,
    update_preset: Optional[str],
    layers: Dict[str, dict],
    style: Dict[str, dict],
    circle: Optional[bool],
    radius: Optional[Union[float, bool]],
    dilate: Optional[Union[float, bool]],
    logging=False,
) -> Tuple[
    dict,
    dict,
    Optional[float],
    Optional[Union[float, bool]],
    Optional[Union[float, bool]],
]:
    """_summary_

    Args:
        load_preset (Optional[str]): Load preset named 'load_preset', if provided
        save_preset (Optional[str]): Save preset to file named 'save_preset', if provided
        update_preset (Optional[str]): Load, update and save preset named 'update_preset', if provided
        layers (Dict[str, dict]): prettymaps.plot() 'layers' parameter dict
        style (Dict[str, dict]): prettymaps.plot() 'style' parameter dict
        circle (Optional[bool]): prettymaps.plot() 'circle' parameter
        radius (Optional[Union[float, bool]]): prettymaps.plot() 'radius' parameter
        dilate (Optional[Union[float, bool]]): prettymaps.plot() 'dilate' parameter

    Returns:
        Tuple[dict, dict, Optional[float], Optional[Union[float, bool]], Optional[Union[float, bool]]]: Updated layers, style, circle, radius, dilate parameters
    """

    # Update preset mode: load a preset, update it with additional parameters and update the JSON file
    if update_preset is not None:
        # load_preset = save_preset = True
        load_preset = save_preset = update_preset

    # Load preset (if provided)
    if load_preset is not None:
        layers, style, circle, radius, dilate = override_preset(
            load_preset, layers, style, circle, radius, dilate
        )

    # Save parameters as preset
    if save_preset is not None:
        create_preset(
            save_preset,
            layers=layers,
            style=style,
            circle=circle,
            radius=radius,
            dilate=dilate,
        )

    return layers, style, circle, radius, dilate

multiplot(*subplots, figsize=None, credit={}, **kwargs)

Creates a multiplot using the provided subplots and optional parameters.

Parameters:

subplots : list A list of subplot objects to be plotted. figsize : tuple, optional A tuple specifying the figure size (width, height) in inches. credit : dict, optional A dictionary containing credit information for the plot. *kwargs : dict, optional Additional keyword arguments to customize the plot.

Returns:

None

Source code in prettymaps/draw.py
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
def multiplot(*subplots, figsize=None, credit={}, **kwargs):
    """
    Creates a multiplot using the provided subplots and optional parameters.

    Parameters:
    -----------
    *subplots : list
        A list of subplot objects to be plotted.
    figsize : tuple, optional
        A tuple specifying the figure size (width, height) in inches.
    credit : dict, optional
        A dictionary containing credit information for the plot.
    **kwargs : dict, optional
        Additional keyword arguments to customize the plot.

    Returns:
    --------
    None
    """

    fig = plt.figure(figsize=figsize)
    ax = plt.subplot(111, aspect="equal")

    mode = "plotter" if "plotter" in kwargs and kwargs["plotter"] else "matplotlib"

    subplots_results = [
        plot(
            subplot.query,
            ax=ax,
            multiplot=True,
            **override_params(
                subplot.kwargs,
                {
                    k: v
                    for k, v in kwargs.items()
                    if k != "load_preset" or "load_preset" not in subplot.kwargs
                },
            ),
            show=False,
        )
        for subplot in subplots
    ]

    if mode == "matplotlib":
        ax.axis("off")
        ax.axis("equal")
        ax.autoscale()

override_args(layers, circle, dilate, logging=False)

Override arguments in layers' kwargs

Parameters:

Name Type Description Default
layers dict

prettymaps.plot() Layers parameters dict

required
circle Optional[bool]

prettymaps.plot() 'Circle' parameter

required
dilate Optional[Union[float, bool]]

prettymaps.plot() 'dilate' parameter

required

Returns:

Name Type Description
dict dict

output dict

Source code in prettymaps/draw.py
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
@log_execution_time
def override_args(
    layers: dict,
    circle: Optional[bool],
    dilate: Optional[Union[float, bool]],
    logging=False,
) -> dict:
    """
    Override arguments in layers' kwargs

    Args:
        layers (dict): prettymaps.plot() Layers parameters dict
        circle (Optional[bool]): prettymaps.plot() 'Circle' parameter
        dilate (Optional[Union[float, bool]]): prettymaps.plot() 'dilate' parameter

    Returns:
        dict: output dict
    """
    override_args = ["circle", "dilate"]
    for layer in layers:
        for arg in override_args:
            if arg not in layers[layer]:
                layers[layer][arg] = locals()[arg]
    return layers

override_params(default_dict, new_dict)

Override parameters in 'default_dict' with additional parameters from 'new_dict'

Parameters:

Name Type Description Default
default_dict dict

Default dict to be overriden with 'new_dict' parameters

required
new_dict dict

New dict to override 'default_dict' parameters

required

Returns:

Name Type Description
dict dict

default_dict overriden with new_dict parameters

Source code in prettymaps/draw.py
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
def override_params(default_dict: dict, new_dict: dict) -> dict:
    """
    Override parameters in 'default_dict' with additional parameters from 'new_dict'

    Args:
        default_dict (dict): Default dict to be overriden with 'new_dict' parameters
        new_dict (dict): New dict to override 'default_dict' parameters

    Returns:
        dict: default_dict overriden with new_dict parameters
    """

    final_dict = deepcopy(default_dict)

    for key in new_dict.keys():
        if type(new_dict[key]) == dict:
            if key in final_dict:
                final_dict[key] = override_params(final_dict[key], new_dict[key])
            else:
                final_dict[key] = new_dict[key]
        else:
            final_dict[key] = new_dict[key]

    return final_dict

override_preset(name, layers={}, style={}, circle=None, radius=None, dilate=None)

Read the preset file given by 'name' and override it with additional parameters

Parameters:

Name Type Description Default
name str

description

required
layers Dict[str, dict]

description. Defaults to {}.

{}
style Dict[str, dict]

description. Defaults to {}.

{}
circle Union[float, None]

description. Defaults to None.

None
radius Union[float, None]

description. Defaults to None.

None
dilate Union[float, None]

description. Defaults to None.

None

Returns:

Type Description
Tuple[dict, dict, Optional[float], Optional[Union[float, bool]], Optional[Union[float, bool]]]

Tuple[dict, dict, Optional[float], Optional[Union[float, bool]], Optional[Union[float, bool]]]: Preset parameters overriden by additional provided parameters

Source code in prettymaps/draw.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
def override_preset(
    name: str,
    layers: Dict[str, dict] = {},
    style: Dict[str, dict] = {},
    circle: Optional[float] = None,
    radius: Optional[Union[float, bool]] = None,
    dilate: Optional[Union[float, bool]] = None,
) -> Tuple[
    dict,
    dict,
    Optional[float],
    Optional[Union[float, bool]],
    Optional[Union[float, bool]],
]:
    """
    Read the preset file given by 'name' and override it with additional parameters

    Args:
        name (str): _description_
        layers (Dict[str, dict], optional): _description_. Defaults to {}.
        style (Dict[str, dict], optional): _description_. Defaults to {}.
        circle (Union[float, None], optional): _description_. Defaults to None.
        radius (Union[float, None], optional): _description_. Defaults to None.
        dilate (Union[float, None], optional): _description_. Defaults to None.

    Returns:
        Tuple[dict, dict, Optional[float], Optional[Union[float, bool]], Optional[Union[float, bool]]]: Preset parameters overriden by additional provided parameters
    """

    params = read_preset(name)

    # Override preset with kwargs
    if "layers" in params:
        layers = override_params(params["layers"], layers)
    if "style" in params:
        style = override_params(params["style"], style)
    if circle is None and "circle" in params:
        circle = params["circle"]
    if radius is None and "radius" in params:
        radius = params["radius"]
    if dilate is None and "dilate" in params:
        dilate = params["dilate"]

    # Delete layers marked as 'False' in the parameter dict
    for layer in [key for key in layers.keys() if layers[key] == False]:
        del layers[layer]

    # Return overriden presets
    return layers, style, circle, radius, dilate

plot(query, layers={}, style={}, keypoints={}, preset='default', use_preset=True, save_preset=None, update_preset=None, postprocessing=lambda x: x, circle=None, radius=None, dilate=None, save_as=None, fig=None, ax=None, figsize=(11.7, 11.7), credit={}, mode='matplotlib', multiplot=False, show=True, x=0, y=0, scale_x=1, scale_y=1, rotation=0, logging=False, semantic=False, adjust_aspect_ratio=True)

Plots a map based on a given query and specified parameters. Args: query: The query for the location to plot. This can be a string (e.g., "Porto Alegre"), a tuple of latitude and longitude coordinates, or a custom GeoDataFrame boundary. layers: The OpenStreetMap layers to plot. Defaults to an empty dictionary. style: Matplotlib parameters for drawing each layer. Defaults to an empty dictionary. keypoints: Keypoints to highlight on the map. Defaults to an empty dictionary. preset: Preset configuration to use. Defaults to "default". use_preset: Whether to use the preset configuration. Defaults to True. save_preset: Path to save the preset configuration. Defaults to None. update_preset: Path to update the preset configuration with additional parameters. Defaults to None. circle: Whether to use a circular boundary. Defaults to None. radius: Radius for the circular or square boundary. Defaults to None. dilate: Amount to dilate the boundary. Defaults to None. save_as: Path to save the resulting plot. Defaults to None. fig: Matplotlib figure object. Defaults to None. ax: Matplotlib axes object. Defaults to None. title: Title of the plot. Defaults to None. figsize: Size of the figure. Defaults to (11.7, 11.7). constrained_layout: Whether to use constrained layout for the figure. Defaults to True. credit: Parameters for the credit message. Defaults to an empty dictionary. mode: Mode for plotting ('matplotlib' or 'plotter'). Defaults to "matplotlib". multiplot: Whether to use multiplot mode. Defaults to False. show: Whether to display the plot using matplotlib. Defaults to True. x: Translation parameter in the x direction. Defaults to 0. y: Translation parameter in the y direction. Defaults to 0. scale_x: Scaling parameter in the x direction. Defaults to 1. scale_y: Scaling parameter in the y direction. Defaults to 1. rotation: Rotation parameter in degrees. Defaults to 0. logging: Whether to enable logging. Defaults to False. Returns: Plot: The resulting plot object.

Source code in prettymaps/draw.py
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
def plot(
    query: str | Tuple[float, float] | gp.GeoDataFrame,
    layers: Dict[str, Dict[str, Any]] = {},
    style: Dict[str, Dict[str, Any]] = {},
    keypoints: Dict[str, Any] = {},
    preset: str = "default",
    use_preset: bool = True,
    save_preset: str | None = None,
    update_preset: str | None = None,
    postprocessing: Callable[
        [Dict[str, gp.GeoDataFrame]], Dict[str, gp.GeoDataFrame]
    ] = lambda x: x,
    circle: bool | None = None,
    radius: float | bool | None = None,
    dilate: float | bool | None = None,
    save_as: str | None = None,
    fig: plt.Figure | None = None,
    ax: plt.Axes | None = None,
    figsize: Tuple[float, float] = (11.7, 11.7),
    credit: Dict[str, Any] = {},
    mode: str = "matplotlib",
    multiplot: bool = False,
    show: bool = True,
    x: float = 0,
    y: float = 0,
    scale_x: float = 1,
    scale_y: float = 1,
    rotation: float = 0,
    logging: bool = False,
    semantic: bool = False,
    adjust_aspect_ratio: bool = True,
) -> Plot:
    """
    Plots a map based on a given query and specified parameters.
    Args:
        query: The query for the location to plot. This can be a string (e.g., "Porto Alegre"), a tuple of latitude and longitude coordinates, or a custom GeoDataFrame boundary.
        layers: The OpenStreetMap layers to plot. Defaults to an empty dictionary.
        style: Matplotlib parameters for drawing each layer. Defaults to an empty dictionary.
        keypoints: Keypoints to highlight on the map. Defaults to an empty dictionary.
        preset: Preset configuration to use. Defaults to "default".
        use_preset: Whether to use the preset configuration. Defaults to True.
        save_preset: Path to save the preset configuration. Defaults to None.
        update_preset: Path to update the preset configuration with additional parameters. Defaults to None.
        circle: Whether to use a circular boundary. Defaults to None.
        radius: Radius for the circular or square boundary. Defaults to None.
        dilate: Amount to dilate the boundary. Defaults to None.
        save_as: Path to save the resulting plot. Defaults to None.
        fig: Matplotlib figure object. Defaults to None.
        ax: Matplotlib axes object. Defaults to None.
        title: Title of the plot. Defaults to None.
        figsize: Size of the figure. Defaults to (11.7, 11.7).
        constrained_layout: Whether to use constrained layout for the figure. Defaults to True.
        credit: Parameters for the credit message. Defaults to an empty dictionary.
        mode: Mode for plotting ('matplotlib' or 'plotter'). Defaults to "matplotlib".
        multiplot: Whether to use multiplot mode. Defaults to False.
        show: Whether to display the plot using matplotlib. Defaults to True.
        x: Translation parameter in the x direction. Defaults to 0.
        y: Translation parameter in the y direction. Defaults to 0.
        scale_x: Scaling parameter in the x direction. Defaults to 1.
        scale_y: Scaling parameter in the y direction. Defaults to 1.
        rotation: Rotation parameter in degrees. Defaults to 0.
        logging: Whether to enable logging. Defaults to False.
    Returns:
        Plot: The resulting plot object.
    """

    # 1. Manage presets
    layers, style, circle, radius, dilate = manage_presets(
        preset if use_preset else None,
        save_preset,
        update_preset,
        layers,
        style,
        circle,
        radius,
        dilate,
    )

    # 2. Init matplotlib figure & axis and vsketch object
    fig, ax, vsk = init_plot(
        layers,
        fig,
        ax,
        figsize,
        mode,
        adjust_aspect_ratio=adjust_aspect_ratio,
        logging=logging,
    )

    # 3. Override arguments in layers' kwargs dict
    layers = override_args(layers, circle, dilate, logging=logging)

    # 4. Fetch geodataframes
    start_time = time.time()
    gdfs = get_gdfs(query, layers, radius, dilate, -rotation, logging=logging)
    fetch_time = time.time() - start_time
    print(f"Fetching geodataframes took {fetch_time:.2f} seconds")

    # 5. Apply transformations to GeoDataFrames (translation, scale, rotation)
    gdfs = transform_gdfs(gdfs, x, y, scale_x, scale_y, rotation, logging=logging)

    # 6. Apply a postprocessing function to the GeoDataFrames, if provided
    gdfs = postprocessing(gdfs)

    # 7. Create background GeoDataFrame and get (x,y) bounds
    background, xmin, ymin, xmax, ymax, dx, dy = create_background(
        gdfs, style, logging=logging
    )

    # 8. Draw layers
    draw_layers(layers, gdfs, style, fig, ax, vsk, mode, logging=logging)

    # 9. Draw keypoints
    keypoints = draw_keypoints(keypoints, gdfs, ax, logging=logging)

    # 9. Draw background
    draw_background(background, ax, style, mode, logging=logging)

    # 10. Draw credit message
    draw_credit(ax, background, credit, mode, multiplot, logging=logging)

    # 11. Draw hillshade
    draw_hillshade(
        layers,
        gdfs,
        ax,
        logging=logging,
        **(layers["hillshade"] if "hillshade" in layers else {}),
    )

    # 12. Create Plot object
    plot = Plot(gdfs, fig, ax, background, keypoints)

    # 13. Save plot as image
    if save_as is not None:
        plt.savefig(save_as)

    # 14. Show plot
    if show:
        if mode == "plotter":
            vsk.display()
        elif mode == "matplotlib":
            plt.show()
        else:
            raise Exception(f"Unknown mode {mode}")
    else:
        plt.close()

    return plot

plot_gdf(layer, gdf, ax, mode='matplotlib', vsk=None, palette=None, width=None, union=False, dilate_points=None, dilate_lines=None, **kwargs)

Plot a layer

Parameters:

Name Type Description Default
layer str

layer name

required
gdf GeoDataFrame

GeoDataFrame

required
ax Axes

matplotlib axis object

required
mode str

drawing mode. Options: 'matplotlib', 'vsketch'. Defaults to 'matplotlib'

'matplotlib'
vsk Optional[SketchClass]

Vsketch object. Mandatory if mode == 'plotter'

None
palette Optional[List[str]]

Color palette. Defaults to None.

None
width Optional[Union[dict, float]]

Street widths. Either a dictionary or a float. Defaults to None.

None
union bool

Whether to join geometries. Defaults to False.

False
dilate_points Optional[float]

Amount of dilation to be applied to point (1D) geometries. Defaults to None.

None
dilate_lines Optional[float]

Amount of dilation to be applied to line (2D) geometries. Defaults to None.

None

Raises:

Type Description
Exception

description

Source code in prettymaps/draw.py
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def plot_gdf(
    layer: str,
    gdf: gp.GeoDataFrame,
    ax: matplotlib.axes.Axes,
    mode: str = "matplotlib",
    # vsk: Optional[vsketch.SketchClass] = None,
    vsk=None,
    palette: Optional[List[str]] = None,
    width: Optional[Union[dict, float]] = None,
    union: bool = False,
    dilate_points: Optional[float] = None,
    dilate_lines: Optional[float] = None,
    **kwargs,
) -> None:
    """
    Plot a layer

    Args:
        layer (str): layer name
        gdf (gp.GeoDataFrame): GeoDataFrame
        ax (matplotlib.axes.Axes): matplotlib axis object
        mode (str): drawing mode. Options: 'matplotlib', 'vsketch'. Defaults to 'matplotlib'
        vsk (Optional[vsketch.SketchClass]): Vsketch object. Mandatory if mode == 'plotter'
        palette (Optional[List[str]], optional): Color palette. Defaults to None.
        width (Optional[Union[dict, float]], optional): Street widths. Either a dictionary or a float. Defaults to None.
        union (bool, optional): Whether to join geometries. Defaults to False.
        dilate_points (Optional[float], optional): Amount of dilation to be applied to point (1D) geometries. Defaults to None.
        dilate_lines (Optional[float], optional): Amount of dilation to be applied to line (2D) geometries. Defaults to None.

    Raises:
        Exception: _description_
    """

    # Get hatch and hatch_c parameter
    hatch_c = kwargs.pop("hatch_c") if "hatch_c" in kwargs else None

    # Convert GDF to shapely geometries
    geometries = gdf_to_shapely(
        layer, gdf, width, point_size=dilate_points, line_width=dilate_lines
    )

    # Unite geometries
    if union:
        geometries = shapely.ops.unary_union(GeometryCollection([geometries]))

    if (palette is None) and ("fc" in kwargs) and (type(kwargs["fc"]) != str):
        palette = kwargs.pop("fc")

    for shape in geometries.geoms if hasattr(geometries, "geoms") else [geometries]:
        if mode == "matplotlib":
            if type(shape) in [Polygon, MultiPolygon]:
                # Plot main shape (without silhouette)
                ax.add_patch(
                    PolygonPatch(
                        shape,
                        lw=0,
                        ec=(
                            hatch_c
                            if hatch_c
                            else kwargs["ec"] if "ec" in kwargs else None
                        ),
                        fc=(
                            kwargs["fc"]
                            if "fc" in kwargs
                            else np.random.choice(palette) if palette else None
                        ),
                        **{
                            k: v
                            for k, v in kwargs.items()
                            if k not in ["lw", "ec", "fc"]
                        },
                    ),
                )
                # Plot just silhouette
                ax.add_patch(
                    PolygonPatch(
                        shape,
                        fill=False,
                        **{
                            k: v
                            for k, v in kwargs.items()
                            if k not in ["hatch", "fill"]
                        },
                    )
                )
            elif type(shape) == LineString:
                ax.plot(
                    *shape.xy,
                    c=kwargs["ec"] if "ec" in kwargs else None,
                    **{
                        k: v
                        for k, v in kwargs.items()
                        if k in ["lw", "ls", "dashes", "zorder"]
                    },
                )
            elif type(shape) == MultiLineString:
                for c in shape.geoms:
                    ax.plot(
                        *c.xy,
                        c=kwargs["ec"] if "ec" in kwargs else None,
                        **{
                            k: v
                            for k, v in kwargs.items()
                            if k in ["lw", "lt", "dashes", "zorder"]
                        },
                    )
        elif mode == "plotter":
            if ("draw" not in kwargs) or kwargs["draw"]:

                # Set stroke
                if "stroke" in kwargs:
                    vsk.stroke(kwargs["stroke"])
                else:
                    vsk.stroke(1)

                # Set pen width
                if "penWidth" in kwargs:
                    vsk.penWidth(kwargs["penWidth"])
                else:
                    vsk.penWidth(0.3)

                if "fill" in kwargs:
                    vsk.fill(kwargs["fill"])
                else:
                    vsk.noFill()

                vsk.geometry(shape)
        else:
            raise Exception(f"Unknown mode {mode}")

presets_directory()

Returns the path to the 'presets' directory. This function constructs the path to the 'presets' directory, which is located in the same directory as the current script file. Returns: str: The full path to the 'presets' directory.

Source code in prettymaps/draw.py
698
699
700
701
702
703
704
705
706
707
def presets_directory():
    """
    Returns the path to the 'presets' directory.
    This function constructs the path to the 'presets' directory, which is
    located in the same directory as the current script file.
    Returns:
        str: The full path to the 'presets' directory.
    """

    return os.path.join(pathlib.Path(__file__).resolve().parent, "presets")

read_preset(name)

Read a preset from the presets folder (prettymaps/presets/)

Parameters:

Name Type Description Default
name str

Preset name

required

Returns:

Type Description
Dict[str, dict]

parameters dictionary

Source code in prettymaps/draw.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
def read_preset(name: str) -> Dict[str, dict]:
    """
    Read a preset from the presets folder (prettymaps/presets/)

    Args:
        name (str): Preset name

    Returns:
        (Dict[str,dict]): parameters dictionary
    """
    path = os.path.join(presets_directory(), f"{name}.json")
    with open(path, "r") as f:
        # Load params from JSON file
        params = json.load(f)
    return params

transform_gdfs(gdfs, x=0, y=0, scale_x=1, scale_y=1, rotation=0, logging=False)

Apply geometric transformations to dictionary of GeoDataFrames

Parameters:

Name Type Description Default
gdfs Dict[str, GeoDataFrame]

Dictionary of GeoDataFrames

required
x float

x-axis translation. Defaults to 0.

0
y float

y-axis translation. Defaults to 0.

0
scale_x float

x-axis scale. Defaults to 1.

1
scale_y float

y-axis scale. Defaults to 1.

1
rotation float

rotation angle (in radians). Defaults to 0.

0

Returns:

Type Description
Dict[str, GeoDataFrame]

Dict[str, gp.GeoDataFrame]: dictionary of transformed GeoDataFrames

Source code in prettymaps/draw.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
@log_execution_time
def transform_gdfs(
    gdfs: Dict[str, gp.GeoDataFrame],
    x: float = 0,
    y: float = 0,
    scale_x: float = 1,
    scale_y: float = 1,
    rotation: float = 0,
    logging=False,
) -> Dict[str, gp.GeoDataFrame]:
    """
    Apply geometric transformations to dictionary of GeoDataFrames

    Args:
        gdfs (Dict[str, gp.GeoDataFrame]): Dictionary of GeoDataFrames
        x (float, optional): x-axis translation. Defaults to 0.
        y (float, optional): y-axis translation. Defaults to 0.
        scale_x (float, optional): x-axis scale. Defaults to 1.
        scale_y (float, optional): y-axis scale. Defaults to 1.
        rotation (float, optional): rotation angle (in radians). Defaults to 0.

    Returns:
        Dict[str, gp.GeoDataFrame]: dictionary of transformed GeoDataFrames
    """
    # Project geometries
    gdfs = {
        name: ox.project_gdf(gdf) if len(gdf) > 0 else gdf for name, gdf in gdfs.items()
    }
    # Create geometry collection from gdfs' geometries
    collection = GeometryCollection(
        [GeometryCollection(list(gdf.geometry)) for gdf in gdfs.values()]
    )
    # Translation, scale & rotation
    collection = shapely.affinity.translate(collection, x, y)
    collection = shapely.affinity.scale(collection, scale_x, scale_y)
    collection = shapely.affinity.rotate(collection, rotation)
    # Update geometries
    for i, layer in enumerate(gdfs):
        gdfs[layer].geometry = list(collection.geoms[i].geoms)
        # Reproject
        if len(gdfs[layer]) > 0:
            gdfs[layer] = ox.project_gdf(gdfs[layer], to_crs="EPSG:4326")

    return gdfs

prettymaps.fetch

Prettymaps - A minimal Python library to draw pretty maps from OpenStreetMap Data Copyright (C) 2021 Marcelo Prates

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/.

get_keypoints(perimeter, tags={'place': 'quarter', 'highway': True, 'building': True, 'landuse': True, 'natural': True, 'waterway': True, 'amenity': True, 'leisure': True, 'shop': True, 'public_transport': True, 'tourism': True, 'historic': True, 'barrier': True, 'power': True, 'railway': True, 'cycleway': True, 'footway': True, 'healthcare': True, 'office': True, 'craft': True, 'man_made': True, 'boundary': True})

Extract keypoints from a given perimeter based on specified tags.

Parameters: perimeter (shapely.geometry.Polygon): The polygon representing the area of interest. tags (dict, optional): A dictionary of tags to filter the keypoints. The keys are tag names and the values are booleans indicating whether to include the tag. Default includes a variety of common tags.

Returns: geopandas.GeoDataFrame: A GeoDataFrame containing the keypoints that match the specified tags within the given perimeter.

Source code in prettymaps/fetch.py
 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
def get_keypoints(
    perimeter,
    tags={
        "place": "quarter",
        "highway": True,
        "building": True,
        "landuse": True,
        "natural": True,
        "waterway": True,
        "amenity": True,
        "leisure": True,
        "shop": True,
        "public_transport": True,
        "tourism": True,
        "historic": True,
        "barrier": True,
        "power": True,
        "railway": True,
        "cycleway": True,
        "footway": True,
        "healthcare": True,
        "office": True,
        "craft": True,
        "man_made": True,
        "boundary": True,
    },
):
    """
    Extract keypoints from a given perimeter based on specified tags.

    Parameters:
    perimeter (shapely.geometry.Polygon): The polygon representing the area of interest.
    tags (dict, optional): A dictionary of tags to filter the keypoints. The keys are tag names and the values are booleans indicating whether to include the tag. Default includes a variety of common tags.

    Returns:
    geopandas.GeoDataFrame: A GeoDataFrame containing the keypoints that match the specified tags within the given perimeter.
    """
    keypoints_df = ox.features_from_polygon(perimeter, tags=tags)

    return keypoints_df

merge_tags(layers_dict)

Merge tags from a dictionary of layers into a single dictionary.

Parameters: layers_dict (dict): Dictionary of layers with their respective tags.

Returns: dict: Merged dictionary of tags.

Source code in prettymaps/fetch.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def merge_tags(layers_dict: dict) -> dict:
    """
    Merge tags from a dictionary of layers into a single dictionary.

    Parameters:
    layers_dict (dict): Dictionary of layers with their respective tags.

    Returns:
    dict: Merged dictionary of tags.
    """

    layers_dict = deepcopy(layers_dict)
    merged_tags = {}

    def _merge(d: dict):
        for key, value in d.items():
            if isinstance(value, dict):
                if "tags" in value:
                    for tag_key, tag_value in value["tags"].items():
                        if tag_key in merged_tags:
                            if isinstance(merged_tags[tag_key], list):
                                if isinstance(tag_value, list):
                                    merged_tags[tag_key].extend(tag_value)
                                else:
                                    merged_tags[tag_key].append(tag_value)
                            else:
                                merged_tags[tag_key] = (
                                    [merged_tags[tag_key], tag_value]
                                    if not isinstance(tag_value, list)
                                    else [merged_tags[tag_key]] + tag_value
                                )
                        else:
                            merged_tags[tag_key] = (
                                tag_value
                                if isinstance(tag_value, list)
                                else [tag_value]
                            )
                _merge(value)

    _merge(layers_dict)

    # Simplify lists with a single element
    merged_tags = {
        k: (v[0] if isinstance(v, list) and len(v) == 1 else v)
        for k, v in merged_tags.items()
    }

    return merged_tags

obtain_elevation(gdf)

Download all SRTM elevation tiles for the given polygon in a GeoDataFrame.

Parameters: gdf (GeoDataFrame): GeoDataFrame containing the polygon. output_dir (str): Directory to save the downloaded tiles.

Source code in prettymaps/fetch.py
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
def obtain_elevation(gdf):
    """
    Download all SRTM elevation tiles for the given polygon in a GeoDataFrame.

    Parameters:
    gdf (GeoDataFrame): GeoDataFrame containing the polygon.
    output_dir (str): Directory to save the downloaded tiles.
    """

    # Ensure the GeoDataFrame has a single polygon
    if len(gdf) != 1:
        raise ValueError("GeoDataFrame must contain a single polygon")

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        subprocess.run(
            ["eio", "clean"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )

    # Get the bounding box of the polygon
    bounds = gdf.total_bounds
    min_lon, min_lat, max_lon, max_lat = bounds

    # Configure the bounding box for the elevation library

    output_file = os.path.join(os.getcwd(), "elevation.tif")
    elevation.clip(
        bounds=(min_lon, min_lat, max_lon, max_lat),
        output=output_file,
        margin="10%",
        cache_dir=".",
    )

    # subprocess.run(
    #    [
    #        "gdalwarp",
    #        "-tr",
    #        "30",
    #        "30",
    #        "-r",
    #        "cubic",
    #        "elevation.tif",
    #        "resampled_elevation.tif",
    #    ],
    #    # stdout=subprocess.DEVNULL,
    #    # stderr=subprocess.DEVNULL,
    # )

    raster = rxr.open_rasterio(output_file).squeeze()

    raster = raster.rio.reproject(CRS.from_string(ox.project_gdf(gdf).crs.to_string()))

    # convert to numpy array
    elevation_data = raster.data

    return elevation_data

read_from_cache(perimeter, layer_kwargs, cache_dir='prettymaps_cache')

Read a GeoDataFrame from the cache based on the perimeter and layer arguments.

Parameters: perimeter (GeoDataFrame): The perimeter GeoDataFrame. layer_kwargs (dict): Dictionary of layer arguments. cache_dir (str): Directory to read the cached GeoDataFrame from.

Returns: GeoDataFrame: The cached GeoDataFrame, or None if it does not exist.

Source code in prettymaps/fetch.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def read_from_cache(
    perimeter: GeoDataFrame,
    layer_kwargs: dict,
    cache_dir: str = "prettymaps_cache",
) -> GeoDataFrame:
    """
    Read a GeoDataFrame from the cache based on the perimeter and layer arguments.

    Parameters:
    perimeter (GeoDataFrame): The perimeter GeoDataFrame.
    layer_kwargs (dict): Dictionary of layer arguments.
    cache_dir (str): Directory to read the cached GeoDataFrame from.

    Returns:
    GeoDataFrame: The cached GeoDataFrame, or None if it does not exist.
    """
    np.random.seed(0)
    # Create hash from perimeter
    perimeter_hash = hash(perimeter["geometry"].to_json())
    # Create hash from kwargs
    kwargs_hash = hash(str(layer_kwargs))
    # Join hashes
    hash_str = f"{perimeter_hash}_{kwargs_hash}"

    cache_path = os.path.join(cache_dir, f"{hash_str}.geojson")

    # Check if the gdf is cached
    if os.path.exists(cache_path):
        # Read cached gdf
        return gp.read_file(cache_path)
    else:
        return None

unified_osm_request(perimeter, layers_dict, logging=False)

Unify all OSM requests into one to improve efficiency.

Parameters: perimeter (GeoDataFrame): The perimeter GeoDataFrame. layers_dict (dict): Dictionary of layers to fetch. logging (bool): Enable or disable logging.

Returns: dict: Dictionary of GeoDataFrames for each layer.

Source code in prettymaps/fetch.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
def unified_osm_request(
    perimeter: GeoDataFrame, layers_dict: dict, logging: bool = False
) -> dict:
    """
    Unify all OSM requests into one to improve efficiency.

    Parameters:
    perimeter (GeoDataFrame): The perimeter GeoDataFrame.
    layers_dict (dict): Dictionary of layers to fetch.
    logging (bool): Enable or disable logging.

    Returns:
    dict: Dictionary of GeoDataFrames for each layer.
    """
    # Apply tolerance to the perimeter
    perimeter_with_tolerance = ox.project_gdf(perimeter).buffer(0).to_crs(4326)
    perimeter_with_tolerance = unary_union(perimeter_with_tolerance.geometry).buffer(0)

    # Fetch from perimeter's bounding box, to avoid missing some geometries
    bbox = box(*perimeter_with_tolerance.bounds)

    # Initialize the result dictionary
    gdfs = {}
    ## Read layers from cache
    # for layer, kwargs in layers_dict.items():
    #    gdf = read_from_cache(perimeter, layers_dict[layer])
    #    if gdf is not None:
    #        gdfs[layer] = gdf

    # Combine all tags into a single dictionary for a unified request
    combined_tags = merge_tags(
        {layer: kwargs for layer, kwargs in layers_dict.items() if layer not in gdfs}
    )

    # Fetch all features in one request
    try:
        all_features = ox.features_from_polygon(bbox, tags=combined_tags)
    except Exception as e:
        all_features = GeoDataFrame(geometry=[])

    # Split the features into separate GeoDataFrames based on the layers_dict
    for layer, kwargs in layers_dict.items():
        if layer in gdfs:
            continue
        try:
            if layer in ["streets", "railway", "waterway"]:
                graph = ox.graph_from_polygon(
                    bbox,
                    custom_filter=kwargs.get("custom_filter"),
                    truncate_by_edge=True,
                )
                gdf = ox.graph_to_gdfs(graph, nodes=False)
            elif layer == "sea":
                try:
                    coastline = unary_union(
                        ox.features_from_polygon(
                            bbox, tags={"natural": "coastline"}
                        ).geometry.tolist()
                    )
                    sea_candidates = bbox.difference(coastline.buffer(1e-9)).geoms
                    drive = ox.graph_from_polygon(bbox, network_type="drive")
                    drive = ox.graph_to_gdfs(drive, nodes=False)

                    def filter_candidate(sea_candidate):
                        intersections = drive.geometry.intersects(sea_candidate)
                        if "bridge" in drive.columns:
                            return not any(
                                intersections
                                & (
                                    drive.loc[
                                        drive.geometry.intersects(sea_candidate),
                                        "bridge",
                                    ]
                                    != "yes"
                                )
                            )
                        else:
                            return not any(intersections)

                    sea = unary_union(
                        MultiPolygon(
                            [
                                candidate
                                for candidate in sea_candidates
                                if filter_candidate(candidate)
                            ]
                        ).geoms
                    ).buffer(1e-8)
                    gdf = GeoDataFrame(geometry=[sea], crs=perimeter.crs)
                except:
                    gdf = GeoDataFrame(geometry=[], crs=perimeter.crs)
            else:
                if kwargs.get("osmid") is None:
                    if layer == "perimeter":
                        gdf = perimeter
                    else:
                        layer_tags = kwargs.get("tags")
                        gdf = gp.GeoDataFrame(geometry=[], crs=perimeter.crs)
                        for key, value in layer_tags.items():
                            if isinstance(value, bool) and value:
                                filtered_features = all_features[
                                    ~pd.isna(all_features[key])
                                ]
                            elif isinstance(value, list):
                                filtered_features = all_features[
                                    all_features[key].isin(value)
                                ]
                            else:
                                filtered_features = all_features[
                                    all_features[key] == value
                                ]
                            gdf = pd.concat([gdf, filtered_features], axis=0)
                else:
                    gdf = ox.geocode_to_gdf(kwargs.get("osmid"), by_osmid=True)

            gdf = gdf.copy()
            gdf.geometry = gdf.geometry.intersection(perimeter_with_tolerance)
            gdf.drop(gdf[gdf.geometry.is_empty].index, inplace=True)
            gdfs[layer] = gdf
            # write_to_cache(perimeter, gdf, layers_dict[layer])
        except Exception as e:
            # print(f"Error fetching {layer}: {e}")
            gdfs[layer] = GeoDataFrame(geometry=[])

    return gdfs

write_to_cache(perimeter, gdf, layer_kwargs, cache_dir='prettymaps_cache')

Write a GeoDataFrame to the cache based on the perimeter and layer arguments.

Parameters: perimeter (GeoDataFrame): The perimeter GeoDataFrame. gdf (GeoDataFrame): The GeoDataFrame to cache. layer_kwargs (dict): Dictionary of layer arguments. cache_dir (str): Directory to save the cached GeoDataFrame.

Source code in prettymaps/fetch.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def write_to_cache(
    perimeter: GeoDataFrame,
    gdf: GeoDataFrame,
    layer_kwargs: dict,
    cache_dir: str = "prettymaps_cache",
):
    """
    Write a GeoDataFrame to the cache based on the perimeter and layer arguments.

    Parameters:
    perimeter (GeoDataFrame): The perimeter GeoDataFrame.
    gdf (GeoDataFrame): The GeoDataFrame to cache.
    layer_kwargs (dict): Dictionary of layer arguments.
    cache_dir (str): Directory to save the cached GeoDataFrame.
    """
    np.random.seed(0)
    os.makedirs(cache_dir, exist_ok=True)

    # Create hash from perimeter
    perimeter_hash = hash(perimeter["geometry"].to_json())
    # Create hash from kwargs
    kwargs_hash = hash(str(layer_kwargs))
    # Join hashes
    hash_str = f"{perimeter_hash}_{kwargs_hash}"

    cache_path = os.path.join(cache_dir, f"{hash_str}.geojson")

    # Write gdf to cache
    logging.getLogger().setLevel(logging.CRITICAL)
    if not gdf.empty:
        gdf.to_file(cache_path, driver="GeoJSON")
    logging.getLogger().setLevel(logging.INFO)