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:
BackgroundMixin,ChromeMixinSVG map builder with viewport-based architecture.
Each distinct area (main map, cartouche, zoom) gets its own SvgViewport with independent geographic bounds and clip region.
Layers and elements (title, scale bar, cartouches…) are added with
m + item, which returns a new map, orm.add(item), which adds in place and returnsm. The map is drawn when it is rendered.- 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 alsoautosize().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.
Truefor 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
Nonefor non-deterministic behaviour. Aseed=passed directly toLabeltakes 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(*items)[source]¶
Add layers and elements to the map, in place.
- Parameters:
*items (Layer, Element, or list of them) – Layers (
Choropleth,Basemap…) and elements (Title,ScaleBar,Insets…). Each layer is assigned a uniqueid. A layer already added to another map is copied (its data is shared), so the same layer object can be passed to several maps.- Return type:
- Returns:
Map –
self, to allow chaining.- Raises:
RuntimeError – If the map has already been built (its SVG is final, so a new item would not appear).
TypeError – If an item is neither a layer nor an element.
Examples
>>> m.add(Basemap()).add(Title("Population")) >>> m.add(Basemap(), Choropleth(gdf, column="density"), ScaleBar())
- add_zoom(params)[source]¶
Add a zoom window. Same as
m.add(Zoom(**params)).See
Zoomfor the parameters. Returns the zoom viewport.- Return type:
SvgViewport
- 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). Returnsselffor chaining.
- property cartouche_viewports: dict[int, SvgViewport]¶
All cartouche viewports.
- property classification_reports: dict¶
Classification report of each Choropleth, keyed by layer id.
Filled when the map is built (
render,svg…). Each report gives the method really applied, the bounds, the number of features per class, the excluded values and any automatic adjustment.
- copy()[source]¶
Return an unbuilt copy of the map.
The copy is rebuilt from the constructor arguments and the layers and elements added so far. Layers are copied; their data is shared.
- Return type:
- 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 adataset:(a built-in dataset) or apath:(a vector file), with optionalcrs,filter, and CSVjoin, 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:
- Returns:
Map
- get_cartouche_viewport(index)[source]¶
Get a cartouche viewport by index.
- Return type:
SvgViewport|None
- get_layer(layer_id)[source]¶
Return a registered layer by its
id.- Raises:
KeyError – If no layer has that id.
- Return type:
- north_arrow(**kwargs)[source]¶
Add a north arrow. Same as
m.add(NorthArrow(**kwargs)).See
NorthArrowfor the parameters.- Return type:
- property overflow: OverflowRegistry¶
Overflow registry (delegates to internal MapState).
- recipe(path=None)[source]¶
Reproducibility recipe: parameters, data fingerprints, versions.
Returns a plain dict with the mappyng/Python/library versions, the seed, the map document (as in
to_yaml()), a SHA-256 fingerprint of the main geometry and of each layer’s data, and the classification reports of the thematic layers already built (call it afterrender). Written to path (YAML for.yaml/.yml, JSON otherwise) when given.- Return type:
dict
- 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..htmlwrites the interactive export (seeto_interactive())..pngand.pdfare rendered from the SVG via the optionalcairosvgdependency (pip install mappyng[export]); the SVG remains the canonical source.- Parameters:
path (str) – Destination file path. The extension selects the format:
.svg(default),.html,.pngor.pdf.dpi (int) – Resolution for PNG export (ignored for SVG and PDF). Defaults to
EXPORT_DEFAULT_DPI.
- Return type:
- Returns:
Map –
self, to allow chaining.- Raises:
ValueError – If the extension is none of
.svg,.html,.png,.pdf.ImportError – If a PNG/PDF export is requested but
cairosvgis not installed.
- save_interactive(path, columns=None, aliases=None, tooltip=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 – See
to_interactive().title (str) – HTML page title.
- Return type:
None
- scale_bar(**kwargs)[source]¶
Add a scale bar. Same as
m.add(ScaleBar(**kwargs)).See
ScaleBarfor the parameters.- Return type:
- source(text, **kwargs)[source]¶
Add a source line. Same as
m.add(Source(text, **kwargs)).See
Sourcefor the parameters.- Return type:
- title(text, **kwargs)[source]¶
Add a title. Same as
m.add(Title(text, **kwargs)).See
Titlefor the parameters.- Return type:
- to_interactive(columns=None, aliases=None, tooltip=None)[source]¶
Export the map as an interactive SVG with hover tooltips.
Returns an
InteractiveMapthat auto-renders in Jupyter and can be saved as standalone HTML. Arguments left to None take their value from theTooltipadded to the map, if any.- 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:
- Returns:
InteractiveMap – Object with
_repr_html_()and.save(path)methods.
Examples
>>> 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.