Skip to content

Python API

pixel-map is a command line tool, but its map can be printed from Python too:

from pixel_map.plotter import plot_geo_data

plot_geo_data(["buildings.parquet"], renderer="block", basemap_provider="OpenFreeMap.Dark")

Plotting functionality.

Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of unicode characters.

BasemapError

Bases: ValueError

Basemap that cannot be drawn.

Source code in pixel_map/plotter.py
class BasemapError(ValueError):
    """Basemap that cannot be drawn."""

plot_geo_data

plot_geo_data(files: list[str], renderer: str, bbox: tuple[float, float, float, float] | None = None, color: str | list[str] = 'C0', alpha: float | list[float] = 1.0, basemap_provider: str | None = None, background_color: str | None = None, no_border: bool = False, console_width: int | None = None, console_height: int | None = None, plotting_dpi: int = 8) -> None

Plot the geo data into a terminal.

Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of unicode characters.

Parameters:

Name Type Description Default
files list[str]

List of files to plot.

required
renderer str

A name for the renderer used to generate terminal output. Defaults to "block".

required
bbox Optional[tuple[float, float, float, float]]

Bounding box used to clip the geo data. Defaults to None.

None
color Union[str, list[str]]

Color or list of colors used to plot geo data. If a list, must be the same length as a number of files. Defaults to "C0".

'C0'
alpha Union[str, list[float]]

Opacity or list of opacities used to plot geo data. If a list, must be the same length as a number of files. Defaults to 1.

1.0
basemap_provider str

A basemap used to plot under the geo data: a name of basemaplibre.STYLES, a URL or a path of a MapLibre style JSON, or anything that contextily draws, if it's installed. Defaults to None.

None
background_color str

Background color. Used then basemap_provider is None. Defaults to None.

None
no_border bool

Removes the border around the map. Defaults to False.

False
console_width int

Console width. Can be used to set arbitrary value. Defaults to None.

None
console_height int

Console height. Can be used to set arbitrary value. Defaults to None.

None
plotting_dpi int

Quality of matplotlib figure. It's used to multiply terminal size by some value to get better quality plot. Defaults to 8.

8
Source code in pixel_map/plotter.py
def plot_geo_data(
    files: list[str],
    renderer: str,
    bbox: tuple[float, float, float, float] | None = None,
    color: str | list[str] = "C0",
    alpha: float | list[float] = 1.0,
    basemap_provider: str | None = None,
    background_color: str | None = None,
    no_border: bool = False,
    console_width: int | None = None,
    console_height: int | None = None,
    plotting_dpi: int = 8,
) -> None:
    """
    Plot the geo data into a terminal.

    Generates a Matplotlib canvas that is rendered to an image and later transformed into a list of
    unicode characters.

    Args:
        files (list[str]): List of files to plot.
        renderer (str): A name for the renderer used to generate terminal output.
            Defaults to "block".
        bbox (Optional[tuple[float, float, float, float]], optional): Bounding box used to clip the
            geo data. Defaults to None.
        color (Union[str, list[str]], optional): Color or list of colors used to plot geo data.
            If a list, must be the same length as a number of files. Defaults to "C0".
        alpha (Union[str, list[float]], optional): Opacity or list of opacities used to plot
            geo data.  If a list, must be the same length as a number of files. Defaults to 1.
        basemap_provider (str, optional): A basemap used to plot under the geo data: a name of
            `basemaplibre.STYLES`, a URL or a path of a MapLibre style JSON, or anything that
            contextily draws, if it's installed. Defaults to None.
        background_color (str, optional): Background color. Used then basemap_provider is None.
            Defaults to None.
        no_border (bool, optional): Removes the border around the map. Defaults to False.
        console_width (int, optional): Console width. Can be used to set arbitrary value.
            Defaults to None.
        console_height (int, optional): Console height. Can be used to set arbitrary value.
            Defaults to None.
        plotting_dpi (int, optional): Quality of matplotlib figure. It's used to multiply terminal
            size by some value to get better quality plot. Defaults to 8.
    """
    force_terminal = os.getenv("FORCE_TERMINAL_MODE", "false").lower() == "true"
    if force_terminal:
        console = Console(force_interactive=False, force_jupyter=False, force_terminal=True)
    else:
        console = get_console()

    if console_width:
        console.width = console_width

    if console_height:
        console.height = console_height

    if no_border:
        terminal_width = console.width
        terminal_height = console.height - 1
    else:
        terminal_width = console.width - 2
        terminal_height = console.height - 3  # 2 for panel and 1 for new line

    map_width = terminal_width
    map_height = terminal_height * 2

    map_ratio = map_width / map_height

    with _get_progress_object(console) as progress:
        progress.add_task("Calculating bounding box", total=None)
        bbox_axes_bounds = None
        if bbox:
            bbox, bbox_axes_bounds = _expand_bbox_to_match_ratio(bbox, ratio=map_ratio)

    with _get_progress_object(console) as progress:
        progress.add_task("Loading Geo data", total=None)
        gdfs = _load_geo_data(files, bbox=bbox)
        if bbox:
            gdfs = [gdf.clip_by_rect(*bbox) for gdf in gdfs]

    with _get_progress_object(console) as progress:
        progress.add_task("Plotting geo data", total=None)
        f, ax = plt.subplots(figsize=(map_width, map_height), dpi=plotting_dpi)

        ax.set_axis_off()
        ax.set_xticks([])
        ax.set_yticks([])

        f.patch.set_facecolor(background_color)
        canvas = f.canvas
        # gdf.to_crs(3857).plot(ax=ax, alpha=0.4)
        if isinstance(color, str):
            color = [color]
        if isinstance(alpha, (int, float)):
            alpha = [alpha]
        for idx, gdf in enumerate(gdfs):
            plot_color = color[idx % len(color)]
            plot_alpha = alpha[idx % len(alpha)]
            gdf.to_crs(3857).plot(ax=ax, color=plot_color, alpha=plot_alpha)

        if bbox_axes_bounds:
            left, bottom, right, top = bbox_axes_bounds
            ax.set_xlim([left, right])
            ax.set_ylim([bottom, top])

        left, bottom, right, top = _expand_axes_limit_to_match_ratio(ax, ratio=map_ratio)

        ax.set_position((0, 0, 1, 1))

        if basemap_provider:
            _add_basemap(ax, basemap_provider)

        canvas.draw()

        # buffer_rgba() replaces the deprecated (and removed in matplotlib 3.10)
        # tostring_rgb() method.  It returns RGBA data; we keep only RGB.
        # On high-DPI displays (e.g. macOS Retina), get_width_height(physical=True)
        # returns the physical pixel dimensions matching the buffer.  The fallback
        # below handles older backends that lack the physical= parameter.
        image_flat = np.frombuffer(canvas.buffer_rgba(), dtype="uint8")  # (H * W * 4,)
        canvas_w, canvas_h = canvas.get_width_height(physical=True)
        total_pixels = len(image_flat) // 4
        if canvas_w * canvas_h != total_pixels:
            # Derive actual physical dimensions from the pixel count and the
            # logical aspect ratio, avoiding lossy rounding of the scale factor.
            canvas_h = round((total_pixels * canvas_h / canvas_w) ** 0.5)
            canvas_w = total_pixels // canvas_h
        image = image_flat.reshape(canvas_h, canvas_w, 4)[:, :, :3]

    with _get_progress_object(console) as progress:
        progress.add_task("Rendering geo data", total=None)
        renderer_object = AVAILABLE_RENDERERS[renderer](
            terminal_width=terminal_width, terminal_height=terminal_height
        )
        characters, foreground_colors, background_colors = renderer_object.render_numpy(image)
        full_rich_string = _construct_full_rich_string(
            characters, foreground_colors, background_colors
        )

    if no_border:
        console.print(full_rich_string)
    else:
        title = _generate_panel_title(files, terminal_width)

        map_minx, map_miny = TRANSFORMER.transform(
            left, bottom, direction=TransformDirection.INVERSE
        )
        map_maxx, map_maxy = TRANSFORMER.transform(right, top, direction=TransformDirection.INVERSE)
        subtitle = _generate_panel_subtitle(
            map_minx, map_miny, map_maxx, map_maxy, terminal_width, terminal_height
        )

        console.print(
            Panel.fit(
                full_rich_string,
                padding=0,
                title=title,
                subtitle=subtitle,
                box=HEAVY,
            )
        )

get_predefined_dark_style

get_predefined_dark_style() -> tuple[str, str]

Get default background and color for dark style.

Source code in pixel_map/plotter.py
def get_predefined_dark_style() -> tuple[str, str]:
    """Get default background and color for dark style."""
    return "OpenFreeMap.Dark", "C1"

get_predefined_light_style

get_predefined_light_style() -> tuple[str, str]

Get default background and color for light style.

Source code in pixel_map/plotter.py
def get_predefined_light_style() -> tuple[str, str]:
    """Get default background and color for light style."""
    return "OpenFreeMap.Positron", "C0"