Skip to content

carto_flow.flow_cartogram.cartogram

Cartogram result class with rich interface.

A cartogram is the result of morphing geometries to make their areas proportional to data values. This module provides the Cartogram class which contains morphed geometries, convergence metrics, and methods for visualization, export, and serialization.

Classes:

  • Cartogram

    A cartogram with morphed geometries, metadata, and convenience methods.

Examples:

>>> from carto_flow import morph_gdf
>>>
>>> cartogram = morph_gdf(gdf, 'population')
>>> print(f"Status: {cartogram.status}")
>>> print(f"Mean error: {cartogram.get_errors().mean_error_pct:.1f}%")
>>> cartogram.plot()
>>> gdf_result = cartogram.to_geodataframe()

Cartogram dataclass

Cartogram(
    snapshots: History,
    convergence: Optional[ConvergenceHistory] = None,
    status: MorphStatus = None,
    niterations: int = 0,
    duration: float = 0.0,
    options: Optional[MorphOptions] = None,
    grid: Optional[Grid] = None,
    target_density: float | None = None,
    internals: Optional[History] = None,
    _source_gdf: Any | None = None,
    _source_landmarks_gdf: Any | None = None,
    _value_column: str | None = None,
)

A cartogram with morphed geometries and metadata.

This class represents the result of a cartogram morphing operation, containing the morphed geometries, convergence status, error metrics, and methods for visualization, export, and serialization.

Attributes:

  • snapshots (History) –

    Collection of CartogramSnapshot objects capturing algorithm state at saved iterations. Access final results via latest property.

  • status (MorphStatus) –

    Computation status (ORIGINAL, CONVERGED, STALLED, COMPLETED, FAILED).

  • niterations (int) –

    Number of iterations completed.

  • duration (float) –

    Computation time in seconds.

  • options ((MorphOptions, optional)) –

    Options used for this computation.

  • grid ((Grid, optional)) –

    Grid used for computation.

  • target_density ((float, optional)) –

    Target equilibrium density.

  • internals ((History, optional)) –

    Internal computation data (if save_internals=True).

Examples:

>>> cartogram = morph_gdf(gdf, 'population')
>>> print(f"Status: {cartogram.status}")
>>> print(f"Mean error: {cartogram.get_errors().mean_error_pct:.1f}%")
>>> cartogram.plot()
>>> gdf_result = cartogram.to_geodataframe()

Methods:

  • __repr__

    Concise string representation.

  • get_convergence_errors

    Get scalar error metrics from convergence history.

  • get_coords

    Get displaced coordinates for a specific iteration.

  • get_density

    Get density values for a specific iteration.

  • get_errors

    Get error metrics for a specific iteration.

  • get_geometry

    Get geometry sequence for a specific iteration.

  • get_landmarks

    Get landmark geometries for a specific iteration.

  • load

    Load cartogram from file.

  • plot

    Plot the cartogram.

  • save

    Save cartogram to file.

  • to_geodataframe

    Export cartogram as GeoDataFrame.

latest property

latest: Optional[CartogramSnapshot]

Get the most recent snapshot.

Returns:

__repr__

__repr__() -> str

Concise string representation.

get_convergence_errors

get_convergence_errors(
    iteration: int | None = None,
) -> Optional[ErrorRecord]

Get scalar error metrics from convergence history.

Unlike get_errors() which returns full MorphErrors from snapshots (only available at snapshot intervals), this method accesses the lightweight convergence history that records scalar metrics for every iteration.

Parameters:

  • iteration (int, default: None ) –

    Iteration number. If None, returns the last recorded iteration.

Returns:

  • ErrorRecord or None

    Scalar error metrics, or None if convergence history not available.

get_coords

get_coords(iteration: int | None = None) -> Any

Get displaced coordinates for a specific iteration.

Parameters:

  • iteration (int, default: None ) –

    Iteration number. If None, returns latest.

Returns:

  • array - like or None

    Displaced coordinates, or None if not available.

get_density

get_density(
    iteration: int | None = None,
) -> np.ndarray | None

Get density values for a specific iteration.

Parameters:

  • iteration (int, default: None ) –

    Iteration number. If None, returns latest.

Returns:

  • ndarray or None

    Density values per geometry.

get_errors

get_errors(
    iteration: int | None = None,
) -> Optional[MorphErrors]

Get error metrics for a specific iteration.

Parameters:

  • iteration (int, default: None ) –

    Iteration number. If None, returns latest.

Returns:

  • MorphErrors or None

    Error metrics, or None if not available.

get_geometry

get_geometry(iteration: int | None = None) -> Any

Get geometry sequence for a specific iteration.

Parameters:

  • iteration (int, default: None ) –

    Iteration number. If None, returns latest.

Returns:

  • array - like

    Sequence of geometries.

get_landmarks

get_landmarks(iteration: int | None = None) -> Any

Get landmark geometries for a specific iteration.

Parameters:

  • iteration (int, default: None ) –

    Iteration number. If None, returns latest.

Returns:

  • array - like or None

    Landmark geometries, or None if not available.

load classmethod

load(path: str | Path) -> Cartogram

Load cartogram from file.

Parameters:

  • path (str) –

    Input file path (JSON format).

Returns:

Examples:

>>> cartogram = Cartogram.load('output/cartogram.json')

plot

plot(
    column: str | None = None,
    iteration: int | None = None,
    cmap: str = "RdYlGn_r",
    legend: bool = True,
    ax: Any | None = None,
    **kwargs,
) -> CartogramPlotResult

Plot the cartogram.

Parameters:

  • column (str, default: None ) –

    Column to use for coloring. Special values: - '_morph_error_pct': Percentage errors (default) - '_morph_density': Density values - Any column from source GeoDataFrame If None, plots without color mapping.

  • iteration (int, default: None ) –

    Which iteration to plot (default: latest).

  • cmap (str, default: 'RdYlGn_r' ) –

    Matplotlib colormap name.

  • legend (bool, default: True ) –

    Show colorbar legend.

  • ax (Axes, default: None ) –

    Axes to plot on. If None, creates new figure.

  • **kwargs

    Additional arguments passed to GeoDataFrame.plot().

Returns:

  • CartogramPlotResult

    Result with the axes and named artist references.

Examples:

>>> cartogram.plot()
>>> cartogram.plot(column='population', cmap='Blues')

save

save(path: str | Path) -> None

Save cartogram to file.

Parameters:

  • path (str) –

    Output file path. Supported formats: - '.json': JSON format (metadata + GeoJSON geometries) - '.gpkg', '.shp', etc.: GeoDataFrame export via to_geodataframe()

Examples:

>>> cartogram.save('output/cartogram.json')
>>> cartogram.save('output/cartogram.gpkg')

to_geodataframe

to_geodataframe(
    iteration: int | None = None,
    include_errors: bool = True,
    include_density: bool = True,
) -> gpd.GeoDataFrame

Export cartogram as GeoDataFrame.

Creates a GeoDataFrame with the morphed geometries and optionally includes error and density columns.

Parameters:

  • iteration (int, default: None ) –

    Which iteration snapshot to export (default: latest).

  • include_errors (bool, default: True ) –

    Add '_morph_error_pct' column with percentage errors.

  • include_density (bool, default: True ) –

    Add '_morph_density' column with density values.

Returns:

  • GeoDataFrame

    Copy of source GeoDataFrame with morphed geometry and metrics.

Raises:

  • ValueError

    If no source GeoDataFrame is available or iteration not found.

Examples:

>>> cartogram = morph_gdf(gdf, 'population')
>>> result_gdf = cartogram.to_geodataframe()
>>> result_gdf.plot(column='_morph_error_pct', cmap='RdYlGn_r')