Skip to content

Support for Basemap #918

Open
Open
@has2k1

Description

@has2k1

@nimisha-18, I was able to add a basemap by implementing a custom geom subtype that adds the basemap during plotnine.ggplot's draw phase:

from __future__ import annotations

import typing

import pandas as pd
from plotnine.geoms.geom import geom
import contextily as ctx

if typing.TYPE_CHECKING:
    from typing import Any

    import pandas as pd
    from matplotlib.axes import Axes

    from plotnine.coords.coord import coord
    from plotnine.iapi import panel_view


class geom_basemap(geom):
    DEFAULT_PARAMS = {
        "stat": "identity",
        "position": "identity",
        "na_rm": False,
        "crs": "EPSG:3857",
        "source": ctx.providers.OpenStreetMap.Mapnik,
    }

    def draw_panel(
        self,
        data: pd.DataFrame,
        panel_params: panel_view,
        coord: coord,
        ax: Axes,
        **params: Any,
    ):
        crs = params["crs"]
        source = params["source"]
        ctx.add_basemap(ax, crs=crs, source=source)

To use it in your example, you would just add it like any other layer:

plot3 = plot2 + geom_basemap(source=ctx.providers.OpenStreetMap.Mapnik)
plot3.show()

Aside, the geom_basemap concept as a geom, at least to me, doesn't fit well with the ideas outlines in The Grammar of Graphics. Im not sure what category a basemap falls within so calling this a geom is likely conceptually incorrect. Just something to think about.

Originally posted by @aaraney in #850 (reply in thread)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions