Map

class mappyng.Map(gdf, bbox=None, width=800, height=600, padding=20, style='classic', facecolor=None, background=None, basemap_color=None, border_radius=0.0, box_shadow=None, glow=None, cartouche_params=None, cartouche_spacing=None, font_scale='auto', coordinate_precision=2, seed=42)[source]

Bases: object

SVG map builder with viewport-based architecture.

Each distinct area (main map, cartouche, zoom) gets its own SvgViewport with independent geographic bounds and clip region.

Parameters:
  • gdf (geopandas.GeoDataFrame) – Base GeoDataFrame defining the map extent and basemap geometry.

  • bbox (list, optional) – Bounding box [minx, miny, maxx, maxy]. If None, computed from gdf.

  • width (float or “auto”) – SVG document width in pixels. "auto" derives the width from the data aspect ratio (the height is then the fixed reference).

  • height (float or “auto”) – SVG document height in pixels. "auto" derives the height from the data aspect ratio so the map is not letterboxed (width stays fixed). See also autosize().

  • padding (float) – Document-level padding in pixels.

  • style (str or dict) – Style name ("classic", "modern") or a dict with "base" key selecting the starting preset and other keys overriding specific style values (e.g. "title_color").

  • facecolor (str, optional) – Ocean/background color drawn inside each viewport.

  • background (str, optional) – Document background color (default white).

  • basemap_color (str, optional) – Override fill color for basemap polygons.

  • border_radius (float) – Corner radius in pixels for the main map viewport (0 = sharp).

  • box_shadow (bool or dict, optional) – Drop-shadow effect on the main map viewport. True for defaults, dict for custom (dx, dy, blur, color, opacity).

  • glow (bool or dict, optional) – Outer glow effect on the main map viewport.

  • cartouche_params (dict, optional) – Cartouche definitions. Keys are integer indices, values are dicts with required keys ‘bbox’ and ‘crs’, plus optional ‘cartouche_title’, ‘cartouche_title_size’, ‘size’, ‘border_radius’, ‘box_shadow’, ‘glow’.

  • cartouche_spacing (float, optional) – Vertical spacing between cartouches in pixels. If None, uses the default figure-fraction layout (mappyng convention).

  • font_scale (float or "auto", default "auto") – Global font size multiplier applied to titles, scale bar, and legends. "auto" computes the scale from the document area so that fonts look consistent across different map sizes.

  • coordinate_precision (int, default 2) – Decimal places kept for geometry path coordinates in the SVG output. Lower values shrink the file and speed up parsing at the cost of sub-pixel accuracy. Points that round to the same position are merged, which also reduces dense geometries.

  • seed (int or None, optional) – Random seed for reproducible stochastic components (currently automatic label placement). Defaults to 42, which keeps maps reproducible across runs. Pass None for non-deterministic behaviour. A seed= passed directly to LabelLayer takes precedence over this map-level seed.

__init__(gdf, bbox=None, width=800, height=600, padding=20, style='classic', facecolor=None, background=None, basemap_color=None, border_radius=0.0, box_shadow=None, glow=None, cartouche_params=None, cartouche_spacing=None, font_scale='auto', coordinate_precision=2, seed=42)[source]
add(layer)[source]

Register a first-class Layer.

The layer is validated and assigned a unique id, then queued for rendering when the map is built (deferred, in z_index order).

Parameters:

layer (Layer) – The layer to add.

Return type:

Layer

Returns:

Layer – The same layer, now carrying its assigned id.

Raises:
  • RuntimeError – If the map has already been built (its SVG is final, so a new layer would not appear).

  • TypeError – If layer is not a Layer.

add_radial_gradient(stops, *, gradient_id=None, cx=0.5, cy=0.5, r=0.5, fx=None, fy=None, units='objectBoundingBox', spread='pad')[source]

Define a radial gradient and return a fill reference.

The returned string is a "url(#id)" usable as the fill of any layer. Offsetting the focal point (fx, fy) from the centre fakes a highlight, turning a flat disc into a lit sphere.

Parameters:
  • stops (list of tuple) – Colour stops from centre to edge: (offset, color) or (offset, color, opacity), offset in [0, 1].

  • gradient_id (str, optional) – Explicit element id. A unique id is generated if omitted.

  • cx, cy (float, default 0.5) – Centre of the gradient. In the default "objectBoundingBox" units these are fractions of the filled shape’s bounding box.

  • r (float, default 0.5) – Radius of the gradient.

  • fx, fy (float, optional) – Focal point. Offsetting it from the centre fakes a highlight. Defaults to (cx, cy).

  • units (str, default "objectBoundingBox") – "objectBoundingBox" (fractions of the shape) or "userSpaceOnUse" (absolute SVG coordinates).

  • spread (str, default "pad") – spreadMethod: "pad", "reflect" or "repeat".

Return type:

str

Returns:

str – A "url(#id)" string.

Examples

ocean = m.add_radial_gradient(
    [(0.0, "#bfe6ff"), (1.0, "#0b3a57")], fx=0.35, fy=0.35)
m.add(VectorLayer(disc, fill=ocean))
add_shadow(gdf, params=None)[source]

Add a drop-shadow layer for the given geometries.

Parameters:
  • gdf (GeoDataFrame) – Geometries to shadow.

  • params (dict, optional) – Shadow configuration:

    • query (str): pandas query to filter gdf (e.g. "code_pays_iso3=='FRA'").

    • dx (float): horizontal offset px.

    • dy (float): vertical offset px.

    • stdDeviation (float): blur radius.

    • color (str): shadow color.

    • opacity (float): shadow opacity 0-1.

    • fill (str): fill of the shadow shape.

    • on_cartouches (bool): propagate to cartouches (default True).

    • on_zoom (bool): propagate to zoom (default False).

  • Example::

    m.add_shadow(gdf_ue, {“query”: “code_pays_iso3==’FRA’”,

    “on_cartouches”: True})

Return type:

None

add_zoom(params)[source]

Add a zoom window showing a magnified area.

Parameters (dict keys)

bboxlist

Geographic bounding box [minx, miny, maxx, maxy] (required).

x, yfloat, optional

Position in SVG pixels (defaults to mappyng figure-fraction).

width, heightfloat, optional

Zoom window size in pixels.

border_colorstr, optional

Border color.

border_widthfloat

Border stroke width.

border_radiusfloat

Corner radius in pixels (0 = sharp corners).

box_shadowbool or dict

Drop shadow behind the zoom window. True for defaults; dict to override keys (dx, dy, blur, color, opacity).

glowbool or dict

Outer glow effect.

rtype:

SvgViewport

returns:
  • SvgViewport

  • Example::

    m.add_zoom({“bbox”: [586377, 6780533, 739396, 6904563],

    “border_radius”: 8, “box_shadow”: True})

autosize()[source]

Recompute the document so the content area fits the data exactly.

Snaps the height to the current data aspect ratio (width fixed), removing aspect-ratio letterboxing. Must be called before add()-ing layers (it rebuilds the canvas and would discard already-rendered content). Returns self for chaining.

property cartouche_viewports: Dict[int, SvgViewport]

All cartouche viewports.

classmethod from_yaml(source, gdf=None, data=None, base_dir=None)[source]

Rebuild a map from a YAML file path or string.

The serialised form stores layers by reference, not geometry, so the geometry has to come from somewhere. Either supply it with gdf (and optionally per-layer data), or let the document carry its own sources: a data: block with a dataset: (a built-in dataset) or a path: (a vector file) — optionally with crs, filter and a CSV join — on the map or on each layer. A fully source-bearing document builds with no Python at all.

Parameters:
  • source (str) – A YAML file path or a YAML string.

  • gdf (GeoDataFrame, optional) – Base geometry. When given, declared sources are ignored.

  • data (dict, optional) – Per-layer geometry override, keyed by layer id.

  • base_dir (str, optional) – Directory that relative path: entries resolve against. Defaults to the YAML file’s directory (or the cwd for a string).

Return type:

Map

Returns:

Map

get_cartouche_viewport(index)[source]

Get a cartouche viewport by index.

Return type:

Optional[SvgViewport]

get_layer(layer_id)[source]

Return a registered layer by its id.

Raises:

KeyError – If no layer has that id.

Return type:

Layer

property layers: List[Layer]

The registered first-class layers, in insertion order (copy).

north_arrow(*, location=<unset>, position=<unset>, size=<unset>, color=<unset>, margin=<unset>, label=<unset>, font_size=<unset>, stroke_width=<unset>, rotation=<unset>)[source]

Add a discreet north arrow.

By convention the top of the map is north, so a north arrow is only needed to lift an ambiguity. The arrow points up; pass rotation only when the map itself is rotated.

Parameters:
  • location (str, optional) – Preset corner: "upper right" (default), "upper left", "lower right" or "lower left".

  • position (dict, optional) – Manual placement {"x": frac, "y": frac} relative to the content area (overrides location).

  • size (float, optional) – Total arrow height in SVG pixels (default 24).

  • color (str, optional) – Color for shaft, arrowhead and label.

  • margin (float, optional) – Distance from the content edge in pixels (default 15).

  • label (str, optional) – Text above the arrow (default "N"; pass "" to hide it).

  • font_size (float, optional) – Label font size (default 9).

  • stroke_width (float, optional) – Shaft stroke width (default 1).

  • rotation (float, optional) – Manual rotation in degrees (default 0, points up).

Return type:

None

Examples

>>> m.north_arrow()
>>> m.north_arrow(location="lower left")
>>> m.north_arrow(position={"x": 0.92, "y": 0.08})
property overflow: OverflowRegistry

Overflow registry (delegates to internal MapState).

remove(layer_or_id)[source]

Remove a registered layer, by object or by id.

Parameters:

layer_or_id (Layer or str) – The layer instance or its id.

Raises:
  • KeyError – If no matching layer is registered.

  • RuntimeError – If the map has already been built.

Return type:

None

render(path, dpi=96)[source]

Render the map to a file. Format inferred from the extension.

.svg (or no extension) is written natively. .png and .pdf are rendered from the SVG via the optional cairosvg dependency (pip install mappyng[export]); the SVG remains the canonical source.

Parameters:
  • path (str) – Destination file path. The extension selects the format: .svg (default), .png or .pdf.

  • dpi (int) – Resolution for PNG export (ignored for SVG and PDF). Defaults to EXPORT_DEFAULT_DPI.

Return type:

Map

Returns:

Mapself, to allow chaining.

Raises:
  • ValueError – If the extension is none of .svg, .png, .pdf.

  • ImportError – If a PNG/PDF export is requested but cairosvg is not installed.

save(path, dpi=96)[source]

Deprecated alias of render().

Kept for backward compatibility; emits a DeprecationWarning and forwards to render(). Use m.render(path) instead.

Return type:

Map

save_interactive(path, columns=None, aliases=None, tooltip=None, hover_opacity=None, title='Interactive Map')[source]

Save the map as an interactive HTML file.

Convenience wrapper around to_interactive() + InteractiveMap.save().

Parameters:
  • path (str) – Output file path.

  • columns, aliases, tooltip, hover_opacity – See to_interactive().

  • title (str) – HTML page title.

Return type:

None

scale_bar(*, length=<unset>, label=<unset>, unit=<unset>, unit_factor=<unset>, location=<unset>, position=<unset>, color=<unset>, bar_color=<unset>, tick_color=<unset>, label_color=<unset>, font_size=<unset>, font_weight=<unset>, font_family=<unset>, bar_height=<unset>, tick_height=<unset>, tick_width=<unset>, margin=<unset>, opacity=<unset>)[source]

Add a scale bar.

Parameters:
  • length (float, optional) – Bar length in map CRS units, e.g. metres. If omitted, a round value near 20 percent of the map width is chosen.

  • label (str, optional) – Text above the bar. Auto-generated from length if omitted. Pass "" to suppress the label.

  • unit (str, optional) – Display unit for auto-labels (default "km").

  • unit_factor (float, optional) – Divisor from CRS units to display units (default 1000 for metres to km).

  • location (str, optional) – Preset corner: "lower right", "lower left", "upper right" or "upper left".

  • position (dict, optional) – Manual placement {"x": frac, "y": frac} relative to the content area (overrides location).

  • color (str, optional) – Color for bar, ticks and label (default from style).

  • bar_color (str, optional) – Bar line color (overrides color).

  • tick_color (str, optional) – Tick line color (overrides color).

  • label_color (str, optional) – Label text color (overrides color).

  • font_size (float, optional) – Label font size (default 8).

  • font_weight (str, optional) – Label font weight (default "normal").

  • font_family (str, optional) – Label font family (default sans-serif).

  • bar_height (float, optional) – Bar thickness in SVG pixels (default 3).

  • tick_height (float, optional) – Tick height in SVG pixels (default bar_height + 3).

  • tick_width (float, optional) – Tick stroke width (default 1).

  • margin (float, optional) – Distance from the content edge in pixels (default 15).

  • opacity (float, optional) – Opacity of bar, ticks and label in [0, 1] (default 1).

Return type:

None

Examples

>>> m.scale_bar()
>>> m.scale_bar(length=200000, label="200 km")
>>> m.scale_bar(position={"x": 0.05, "y": 0.95})
source(text, *, layout=<unset>, position=<unset>, rotation=<unset>, font_size=<unset>, color=<unset>, opacity=<unset>, font_style=<unset>, font_weight=<unset>, font_family=<unset>, text_anchor=<unset>)[source]

Add a source or credit line.

Parameters:
  • text (str) – Source text, rendered in italic by default. Use "\n" to split into several lines.

  • layout (str, optional) – "vertical" (default), rotated 90 degrees at the right edge and read bottom to top, or "horizontal" at the bottom-right of the map.

  • position (dict, optional) – Manual placement as {"x": frac, "y": frac} relative to the map content area. Overrides the automatic positioning.

  • rotation (float, optional) – Explicit rotation in degrees. Used only when position is unset (default 90 for vertical, 0 for horizontal).

  • font_size (float, optional) – Font size in points (default from style).

  • color (str, optional) – Text color as #RRGGBB (default from style).

  • opacity (float, optional) – Text opacity in [0, 1] (default from style).

  • font_style (str, optional) – CSS font style (default "italic").

  • font_weight (str, optional) – CSS font weight (default "normal").

  • font_family (str, optional) – Font family (default from style).

  • text_anchor (str, optional) – SVG text anchor: "start", "middle" or "end". Default depends on layout and position.

Return type:

None

Examples

>>> m.source("Source : INSEE")
>>> m.source("Source : INSEE", layout="horizontal")
>>> m.source("Source : INSEE", position={"x": 0.5, "y": 1.05})
title(text, *, subtitle=<unset>, loc=<unset>, max_chars=<unset>, font_size=<unset>, fill=<unset>, font_weight=<unset>, font_family=<unset>, subtitle_font_size=<unset>, subtitle_color=<unset>, subtitle_font_weight=<unset>, top_gap=<unset>, offset_x=<unset>, offset_y=<unset>)[source]

Add a map title above the map content.

Parameters:
  • text (str) – Title text. Wrapped onto several lines past max_chars.

  • subtitle (str, optional) – Subtitle drawn below the title in a lighter style.

  • loc (str, optional) – Horizontal alignment: "left" (default), "center" or "right".

  • max_chars (int, optional) – Maximum characters per line before wrapping.

  • font_size (float, optional) – Title font size in points (default from style).

  • fill (str, optional) – Title color as #RRGGBB (default from style).

  • font_weight (str, optional) – Title font weight, e.g. "bold" (default from style).

  • font_family (str, optional) – Title font family (default from style).

  • subtitle_font_size (float, optional) – Subtitle font size (default derived from font_size).

  • subtitle_color (str, optional) – Subtitle color as #RRGGBB (default: same as fill).

  • subtitle_font_weight (str, optional) – Subtitle font weight (default "normal").

  • top_gap (float, optional) – Vertical gap in pixels between the title baseline and the top of the map content. Positive moves the title up, negative moves it down. Default 8.

  • offset_x (float, optional) – Extra horizontal shift in pixels (positive = right). Default 0.

  • offset_y (float, optional) – Extra vertical shift in pixels (positive = down). Default 0.

Return type:

None

Examples

>>> m.title("Population par departement")
>>> m.title("Population", subtitle="2024", loc="center", font_size=14)
to_interactive(columns=None, aliases=None, tooltip=None, hover_opacity=None)[source]

Export the map as an interactive SVG with hover tooltips.

Returns an InteractiveMap that auto-renders in Jupyter and can be saved as standalone HTML.

Parameters:
  • columns (list of str, optional) – Restrict tooltip to these columns. If None, all non-internal columns are shown.

  • aliases (dict, optional) – Column name to display label mapping, e.g. {"LIB_GEO": "Département"}.

  • tooltip (dict, optional) – Tooltip appearance, any field of TooltipStyle: background, text_color, font_size, font_family, border_radius, key_weight, highlight_opacity.

Return type:

InteractiveMap

Returns:

  • InteractiveMap – Object with _repr_html_() and .save(path) methods.

  • Example::

    m.to_interactive(

    columns=[“LIB_GEO”, “population”], aliases={“LIB_GEO”: “Département”}, tooltip={“background”: “#1a1a2e”, “font_size”: 13},

    )

to_string()[source]

Render the map and return the SVG markup as a string.

Return type:

str

Returns:

str – Self-contained SVG string, ready for embedding or saving.

to_yaml(path=None)[source]

Serialise the map’s intent to YAML.

The output captures the configuration, the ordered layers with their parameters, and the chrome. It does not store the SVG nor the geometry. Geometry is reattached at load time (see from_yaml()).

Parameters:

path (str, optional) – If given, the YAML is also written to this file.

Return type:

str

Returns:

str – The YAML document.

property zoom_viewport: SvgViewport | None

The zoom viewport, if created.