Skip to content

API reference

Bivario.

Python library for plotting bivariate choropleth maps in Matplotlib and Folium.

AccentsBivariateColourmap

Bases: BivariateColourmap

BivariateColourmap defined by 2 colour accents.

Source code in bivario/cmap.py
class AccentsBivariateColourmap(BivariateColourmap):
    """BivariateColourmap defined by 2 colour accents."""

    def __init__(
        self,
        accent_a: ColourType,
        accent_b: ColourType,
        dark_mode: bool = False,
        light: ColourType | None = None,
        dark: ColourType | None = None,
    ) -> None:
        """
        Initialise AccentsBivariateColourmap.

        Args:
            accent_a (ColourType): First colour accent.
            accent_b (ColourType): Second colour accent.
            dark_mode (bool, optional): Whether to use palette in dark mode.
                Swaps light and dark corners (low and high) for better readability on dark
                background. Can also be set during __call__. Defaults to False.
            light (ColourType | None, optional): light corner colour.
                If None, will be (1, 1, 1). Defaults to None.
            dark (ColourType | None, optional): Dark corner colour.
                If None will be (0.15, 0.15, 0.15). Defaults to None.
        """
        self.accent_a = accent_a
        self.accent_b = accent_b
        self.light = light or (1, 1, 1)
        self.dark = dark or (0.15, 0.15, 0.15)
        self.dark_mode = dark_mode

    def __str__(self) -> str:
        """Full representation of the colourmap."""
        return (
            f"<{self.__class__.__name__} (Accent A: {rgb2hex(self.accent_a)}, "
            f"Accent B: {rgb2hex(self.accent_b)}, Light: {rgb2hex(self.light)}, "
            f"Dark: {rgb2hex(self.dark)})>"
        )

    def _apply_colours(
        self,
        values_a: "NumericArray",
        values_b: "NumericArray",
        dark_mode: bool | None = None,
        **kwargs: Any,
    ) -> "BivariateColourmapArray":
        dark_mode = dark_mode if dark_mode is not None else self.dark_mode

        accent_a, accent_b = self.accent_a, self.accent_b

        low = self.dark if dark_mode else self.light
        high = self.light if dark_mode else self.dark

        return CornersBivariateColourmap(
            accent_a=accent_a, accent_b=accent_b, low=low, high=high
        )._apply_colours(values_a, values_b)

__init__

__init__(accent_a: ColourType, accent_b: ColourType, dark_mode: bool = False, light: ColourType | None = None, dark: ColourType | None = None) -> None

Initialise AccentsBivariateColourmap.

Parameters:

Name Type Description Default
accent_a ColourType

First colour accent.

required
accent_b ColourType

Second colour accent.

required
dark_mode bool

Whether to use palette in dark mode. Swaps light and dark corners (low and high) for better readability on dark background. Can also be set during call. Defaults to False.

False
light ColourType | None

light corner colour. If None, will be (1, 1, 1). Defaults to None.

None
dark ColourType | None

Dark corner colour. If None will be (0.15, 0.15, 0.15). Defaults to None.

None
Source code in bivario/cmap.py
def __init__(
    self,
    accent_a: ColourType,
    accent_b: ColourType,
    dark_mode: bool = False,
    light: ColourType | None = None,
    dark: ColourType | None = None,
) -> None:
    """
    Initialise AccentsBivariateColourmap.

    Args:
        accent_a (ColourType): First colour accent.
        accent_b (ColourType): Second colour accent.
        dark_mode (bool, optional): Whether to use palette in dark mode.
            Swaps light and dark corners (low and high) for better readability on dark
            background. Can also be set during __call__. Defaults to False.
        light (ColourType | None, optional): light corner colour.
            If None, will be (1, 1, 1). Defaults to None.
        dark (ColourType | None, optional): Dark corner colour.
            If None will be (0.15, 0.15, 0.15). Defaults to None.
    """
    self.accent_a = accent_a
    self.accent_b = accent_b
    self.light = light or (1, 1, 1)
    self.dark = dark or (0.15, 0.15, 0.15)
    self.dark_mode = dark_mode

__str__

__str__() -> str

Full representation of the colourmap.

Source code in bivario/cmap.py
def __str__(self) -> str:
    """Full representation of the colourmap."""
    return (
        f"<{self.__class__.__name__} (Accent A: {rgb2hex(self.accent_a)}, "
        f"Accent B: {rgb2hex(self.accent_b)}, Light: {rgb2hex(self.light)}, "
        f"Dark: {rgb2hex(self.dark)})>"
    )

CornersBivariateColourmap

Bases: BivariateColourmap

BivariateColourmap defined by 4 corners.

Source code in bivario/cmap.py
class CornersBivariateColourmap(BivariateColourmap):
    """BivariateColourmap defined by 4 corners."""

    def __init__(
        self, accent_a: ColourType, accent_b: ColourType, low: ColourType, high: ColourType
    ) -> None:
        """
        Initialise CornersBivariateColourmap.

        Args:
            accent_a (ColourType): First colour accent.
            accent_b (ColourType): Second colour accent.
            low (ColourType): Low values colour.
            high (ColourType): High values colour.
        """
        self.a_colour = to_rgb(accent_a)
        self.b_colour = to_rgb(accent_b)
        self.low_colour = to_rgb(low)
        self.high_colour = to_rgb(high)

    def __str__(self) -> str:
        """Full representation of the colourmap."""
        return (
            f"<{self.__class__.__name__} (Accent A: {rgb2hex(self.a_colour)}, "
            f"Accent B: {rgb2hex(self.b_colour)}, Low: {rgb2hex(self.low_colour)}, "
            f"High: {rgb2hex(self.high_colour)})>"
        )

    def _apply_colours(
        self, values_a: "NumericArray", values_b: "NumericArray", **kwargs: Any
    ) -> "BivariateColourmapArray":
        z_colour = np.zeros((*values_a.shape, 3), dtype=float)

        a_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(self.a_colour)))
        b_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(self.b_colour)))
        low_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(self.low_colour)))
        high_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(np.array(self.high_colour)))

        it = np.nditer(np.zeros(z_colour.shape[:-1]), flags=["multi_index"])
        while not it.finished:
            pos_a, pos_b = values_a[it.multi_index], values_b[it.multi_index]

            first_colour = _lerp(low_colour_oklab, a_colour_oklab, pos_a)
            second_colour = _lerp(b_colour_oklab, high_colour_oklab, pos_a)
            middle_colour = _lerp(first_colour, second_colour, pos_b)

            mixed_colour_rgb = np.clip(XYZ_to_sRGB(Oklab_to_XYZ(middle_colour)), 0, 1)

            z_colour[it.multi_index] = mixed_colour_rgb
            it.iternext()

        return z_colour

__init__

__init__(accent_a: ColourType, accent_b: ColourType, low: ColourType, high: ColourType) -> None

Initialise CornersBivariateColourmap.

Parameters:

Name Type Description Default
accent_a ColourType

First colour accent.

required
accent_b ColourType

Second colour accent.

required
low ColourType

Low values colour.

required
high ColourType

High values colour.

required
Source code in bivario/cmap.py
def __init__(
    self, accent_a: ColourType, accent_b: ColourType, low: ColourType, high: ColourType
) -> None:
    """
    Initialise CornersBivariateColourmap.

    Args:
        accent_a (ColourType): First colour accent.
        accent_b (ColourType): Second colour accent.
        low (ColourType): Low values colour.
        high (ColourType): High values colour.
    """
    self.a_colour = to_rgb(accent_a)
    self.b_colour = to_rgb(accent_b)
    self.low_colour = to_rgb(low)
    self.high_colour = to_rgb(high)

__str__

__str__() -> str

Full representation of the colourmap.

Source code in bivario/cmap.py
def __str__(self) -> str:
    """Full representation of the colourmap."""
    return (
        f"<{self.__class__.__name__} (Accent A: {rgb2hex(self.a_colour)}, "
        f"Accent B: {rgb2hex(self.b_colour)}, Low: {rgb2hex(self.low_colour)}, "
        f"High: {rgb2hex(self.high_colour)})>"
    )

MplCmapBivariateColourmap

Bases: BivariateColourmap

BivariateColourmap defined by 2 Matplotlib colourmaps.

Source code in bivario/cmap.py
class MplCmapBivariateColourmap(BivariateColourmap):
    """BivariateColourmap defined by 2 Matplotlib colourmaps."""

    def __init__(self, cmap_a: str | Colormap, cmap_b: str | Colormap) -> None:
        """
        Initialise MplCmapBivariateColourmap.

        Args:
            cmap_a (str | Colormap): First colourmap.
            cmap_b (str | Colormap): Second colourmap.
        """
        self.cmap_a = get_cmap(cmap_a)
        self.cmap_b = get_cmap(cmap_b)

    def __str__(self) -> str:
        """Full representation of the colourmap."""
        return f"<{self.__class__.__name__} ({self.cmap_a.name}, {self.cmap_b.name})>"

    def _apply_colours(
        self, values_a: "NumericArray", values_b: "NumericArray", **kwargs: Any
    ) -> "BivariateColourmapArray":
        va_colour = self.cmap_a(values_a)[..., :3]
        vb_colour = self.cmap_b(values_b)[..., :3]

        va_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(va_colour))
        vb_colour_oklab = XYZ_to_Oklab(sRGB_to_XYZ(vb_colour))

        z_colour = np.zeros_like(va_colour, dtype=float)

        it = np.nditer(np.zeros(z_colour.shape[:-1]), flags=["multi_index"])
        while not it.finished:
            pos_a, pos_b = values_a[it.multi_index], values_b[it.multi_index]

            loc_diff = pos_b - pos_a
            lerp_t = (loc_diff + 1) / 2

            colour_a = va_colour_oklab[it.multi_index]
            colour_b = vb_colour_oklab[it.multi_index]

            mixed_colour = _lerp(colour_a, colour_b, lerp_t)
            mixed_colour_rgb = np.clip(XYZ_to_sRGB(Oklab_to_XYZ(mixed_colour)), 0, 1)

            z_colour[it.multi_index] = mixed_colour_rgb
            it.iternext()

        return z_colour

__init__

__init__(cmap_a: str | Colormap, cmap_b: str | Colormap) -> None

Initialise MplCmapBivariateColourmap.

Parameters:

Name Type Description Default
cmap_a str | Colormap

First colourmap.

required
cmap_b str | Colormap

Second colourmap.

required
Source code in bivario/cmap.py
def __init__(self, cmap_a: str | Colormap, cmap_b: str | Colormap) -> None:
    """
    Initialise MplCmapBivariateColourmap.

    Args:
        cmap_a (str | Colormap): First colourmap.
        cmap_b (str | Colormap): Second colourmap.
    """
    self.cmap_a = get_cmap(cmap_a)
    self.cmap_b = get_cmap(cmap_b)

__str__

__str__() -> str

Full representation of the colourmap.

Source code in bivario/cmap.py
def __str__(self) -> str:
    """Full representation of the colourmap."""
    return f"<{self.__class__.__name__} ({self.cmap_a.name}, {self.cmap_b.name})>"

NamedBivariateColourmap

Bases: BivariateColourmap

BivariateColourmap loaded from predefined palettes.

Source code in bivario/cmap.py
class NamedBivariateColourmap(BivariateColourmap):
    """BivariateColourmap loaded from predefined palettes."""

    def __init__(self, name: str, invert_accents: bool = False, dark_mode: bool = False) -> None:
        """
        Initialise NamedBivariateColourmap.

        Args:
            name (str): Name of the predefined palette.
            invert_accents (bool, optional): Whether to swap two colour accents.
                Can also be set during __call__. Defaults to False.
            dark_mode (bool, optional): Whether to use palette in dark mode.
                Swaps light and dark corners (low and high) for better readability on dark
                background. Can also be set during __call__. Defaults to False.
        """
        self.palette_name = name
        loaded_palette = BIVARIATE_CORNER_PALETTES.get(name)
        if loaded_palette is None:
            raise ValueError(
                f"Unrecognized palette: {name}. "
                f"Available palettes: {list(BIVARIATE_CORNER_PALETTES.keys())}."
            )

        self.accent_a, self.accent_b = loaded_palette.accent_a, loaded_palette.accent_b
        self.low, self.high = loaded_palette.low, loaded_palette.high
        self.invert_accents = invert_accents
        self.dark_mode = dark_mode

    def __str__(self) -> str:
        """Full representation of the colourmap."""
        return f"<{self.__class__.__name__} ({self.palette_name})>"

    def _apply_colours(
        self,
        values_a: "NumericArray",
        values_b: "NumericArray",
        invert_accents: bool | None = None,
        dark_mode: bool | None = None,
        **kwargs: Any,
    ) -> "BivariateColourmapArray":
        dark_mode = dark_mode if dark_mode is not None else self.dark_mode
        invert_accents = invert_accents if invert_accents is not None else self.invert_accents

        accent_a, accent_b = self.accent_a, self.accent_b

        if invert_accents:
            accent_a, accent_b = accent_b, accent_a

        low, high = self.low, self.high
        if dark_mode:
            low, high = high, low

        return CornersBivariateColourmap(
            accent_a=accent_a, accent_b=accent_b, low=low, high=high
        )._apply_colours(values_a, values_b)

__init__

__init__(name: str, invert_accents: bool = False, dark_mode: bool = False) -> None

Initialise NamedBivariateColourmap.

Parameters:

Name Type Description Default
name str

Name of the predefined palette.

required
invert_accents bool

Whether to swap two colour accents. Can also be set during call. Defaults to False.

False
dark_mode bool

Whether to use palette in dark mode. Swaps light and dark corners (low and high) for better readability on dark background. Can also be set during call. Defaults to False.

False
Source code in bivario/cmap.py
def __init__(self, name: str, invert_accents: bool = False, dark_mode: bool = False) -> None:
    """
    Initialise NamedBivariateColourmap.

    Args:
        name (str): Name of the predefined palette.
        invert_accents (bool, optional): Whether to swap two colour accents.
            Can also be set during __call__. Defaults to False.
        dark_mode (bool, optional): Whether to use palette in dark mode.
            Swaps light and dark corners (low and high) for better readability on dark
            background. Can also be set during __call__. Defaults to False.
    """
    self.palette_name = name
    loaded_palette = BIVARIATE_CORNER_PALETTES.get(name)
    if loaded_palette is None:
        raise ValueError(
            f"Unrecognized palette: {name}. "
            f"Available palettes: {list(BIVARIATE_CORNER_PALETTES.keys())}."
        )

    self.accent_a, self.accent_b = loaded_palette.accent_a, loaded_palette.accent_b
    self.low, self.high = loaded_palette.low, loaded_palette.high
    self.invert_accents = invert_accents
    self.dark_mode = dark_mode

__str__

__str__() -> str

Full representation of the colourmap.

Source code in bivario/cmap.py
def __str__(self) -> str:
    """Full representation of the colourmap."""
    return f"<{self.__class__.__name__} ({self.palette_name})>"

explore_bivariate_data

explore_bivariate_data(gdf: GeoDataFrame, column_a: str | ValueInput, column_b: str | ValueInput, column_a_label: str | None = None, column_b_label: str | None = None, scheme: SCHEME_TYPE | tuple[SCHEME_TYPE, SCHEME_TYPE] = True, k: int | tuple[int, int] = 5, tiles: str | TileLayer | TileProvider | None = None, cmap: BivariateColourmap | str | None = None, dark_mode: bool | None = None, alpha: bool = True, alpha_norm_quantile: float = 0.9, legend: bool = True, legend_size_px: int = 200, legend_max_grid_size: int | None = 100, legend_loc: Literal['bl', 'br', 'tl', 'tr'] | None = None, legend_offset_px: float | tuple[float, float] | None = None, legend_background: bool = True, legend_border: bool = True, legend_kwargs: dict[str, Any] | None = None, **kwargs: Any) -> Map

Explore geospatial data with a bivariate colormap on a folium map.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Geospatial data to plot.

required
column_a str | ValueInput

Column name for the first variable or list/array of values.

required
column_b str | ValueInput

Column name for the second variable or list/array of values.

required
column_a_label str | None

Label for column a. If None, will use column name. Defaults to None.

None
column_b_label str | None

Label for column b. If None, will use column name. Defaults to None.

None
scheme str | None | bool | tuple

Mapclassify binning scheme for the data. If True, uses "NaturalBreaks". If False, no binning is applied. If str, uses the specified scheme. If None, no binning is applied. Can also define two different values for columns a and b. Defaults to True.

True
k int | tuple[int, int]

Number of classes for binning. Can also define two different values for columns a and b. Defaults to 5.

5
tiles str | TileLayer | TileProvider | None

Tile layer for the map. If None, will set based on dark mode - OpenFreeMap's "Dark" for the dark mode, and "Positron" for the light mode. Defaults to None.

None
cmap BivariateColourmap | str | None

Bivariate colourmap to use. If None, will load a default one. Defaults to None.

None
dark_mode bool | None

Whether to use dark mode for the map tiles. If None, will infer from the tiles if provided, otherwise defaults to False. Defaults to None

None
alpha bool

Whether to apply alpha transparency based on the data values. Will set higher values to be more opaque. It is calculated based on the normalized values of both columns. Defaults to True.

True
alpha_norm_quantile float

Quantile for normalizing alpha transparency. Will be used to calculate the maximum value for alpha scaling. It is recommended to use value below 1 to avoid outliers affecting the transparency too much. Defaults to 0.9.

0.9
legend bool

Whether to add a bivariate legend to the map. Defaults to True.

True
legend_size_px int

Size of the legend in pixels. Defaults to 200.

200
legend_max_grid_size int | None

Max size of the legend grid used for plotting the legend. Used with scheme=False. Defaults to 100.

100
legend_loc Literal['bl', 'br', 'tl', 'tr'] | None

Location of the legend on the map. Can be "bl" (bottom-left), "br" (bottom-right), "tl" (top-left), or "tr" (top-right). Defaults to "bl".

None
legend_offset_px float | tuple[float, float] | None

Offset of the legend from the specified location in pixels. If None, uses default offsets based on location. Defaults to None.

None
legend_background bool

Whether to add a background to the legend. Defaults to True.

True
legend_border bool

Whether to add a border to the legend. Defaults to True.

True
legend_kwargs dict[str, Any] | None

Additional keyword arguments for the legend plotting function. Defaults to None.

None
**kwargs Any

Additional keyword arguments for the folium map.

{}

Returns:

Type Description
Map

folium.Map: Folium map with the bivariate colormap applied.

Examples:

Plot NYC bike trips with morning starts and ends:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import explore_bivariate_data
>>> gdf = nyc_bike_trips()
>>> explore_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="morning_ends",
... )
<folium.folium.Map object at 0x...>

Plot in dark mode with different colormap and different binning:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import explore_bivariate_data
>>> gdf = nyc_bike_trips()
>>> explore_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="morning_ends",
...     column_a_label="Morning Starts",
...     column_b_label="Morning Ends",
...     dark_mode=True,
...     cmap="bubblegum",
...     scheme="Quantiles",
...     k=10,
... )
<folium.folium.Map object at 0x...>

Plot without binning (numerical values) and different legend position:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import explore_bivariate_data
>>> gdf = nyc_bike_trips()
>>> explore_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="afternoon_starts",
...     scheme=False,
...     legend_loc="tr",
...     legend_size_px=300,
... )
<folium.folium.Map object at 0x...>
Source code in bivario/folium/__init__.py
def explore_bivariate_data(
    gdf: "gpd.GeoDataFrame",
    column_a: "str | ValueInput",
    column_b: "str | ValueInput",
    column_a_label: str | None = None,
    column_b_label: str | None = None,
    scheme: SCHEME_TYPE | tuple[SCHEME_TYPE, SCHEME_TYPE] = True,
    k: int | tuple[int, int] = 5,
    tiles: "str | folium.TileLayer | xyzservices.TileProvider | None" = None,
    cmap: BivariateColourmap | str | None = None,
    dark_mode: bool | None = None,
    alpha: bool = True,
    alpha_norm_quantile: float = 0.9,
    legend: bool = True,
    legend_size_px: int = 200,
    legend_max_grid_size: int | None = 100,
    legend_loc: Literal["bl", "br", "tl", "tr"] | None = None,
    legend_offset_px: float | tuple[float, float] | None = None,
    legend_background: bool = True,
    legend_border: bool = True,
    legend_kwargs: dict[str, Any] | None = None,
    **kwargs: Any,
) -> "folium.Map":
    """
    Explore geospatial data with a bivariate colormap on a folium map.

    Args:
        gdf (gpd.GeoDataFrame): Geospatial data to plot.
        column_a (str | ValueInput): Column name for the first variable or list/array of values.
        column_b (str | ValueInput): Column name for the second variable or list/array of values.
        column_a_label (str | None, optional): Label for column a. If None, will use column name.
            Defaults to None.
        column_b_label (str | None, optional): Label for column b. If None, will use column name.
            Defaults to None.
        scheme (str | None | bool | tuple, optional): Mapclassify binning scheme for the data.
            If True, uses "NaturalBreaks". If False, no binning is applied.
            If str, uses the specified scheme. If None, no binning is applied. Can also define
            two different values for columns a and b. Defaults to True.
        k (int | tuple[int, int], optional): Number of classes for binning. Can also define two
            different values for columns a and b. Defaults to 5.
        tiles (str | folium.TileLayer | xyzservices.TileProvider | None, optional): Tile layer
            for the map. If None, will set based on dark mode - OpenFreeMap's "Dark" for the
            dark mode, and "Positron" for the light mode. Defaults to None.
        cmap (BivariateColourmap | str | None, optional): Bivariate colourmap to use.
            If None, will load a default one. Defaults to None.
        dark_mode (bool | None, optional): Whether to use dark mode for the map tiles. If None,
            will infer from the tiles if provided, otherwise defaults to False. Defaults to None
        alpha (bool, optional): Whether to apply alpha transparency based on the data values. Will
            set higher values to be more opaque. It is calculated based on the normalized values of
            both columns. Defaults to True.
        alpha_norm_quantile (float, optional): Quantile for normalizing alpha transparency.
            Will be used to calculate the maximum value for alpha scaling. It is recommended to use
            value below 1 to avoid outliers affecting the transparency too much. Defaults to 0.9.
        legend (bool, optional): Whether to add a bivariate legend to the map. Defaults to True.
        legend_size_px (int, optional): Size of the legend in pixels. Defaults to 200.
        legend_max_grid_size (int | None, optional): Max size of the legend grid used for plotting
            the legend. Used with scheme=False. Defaults to 100.
        legend_loc (Literal["bl", "br", "tl", "tr"] | None, optional): Location of the legend
            on the map. Can be "bl" (bottom-left), "br" (bottom-right), "tl" (top-left),
            or "tr" (top-right). Defaults to "bl".
        legend_offset_px (float | tuple[float, float] | None, optional): Offset of the legend
            from the specified location in pixels. If None, uses default offsets based on location.
            Defaults to None.
        legend_background (bool, optional): Whether to add a background to the legend.
            Defaults to True.
        legend_border (bool, optional): Whether to add a border to the legend. Defaults to True.
        legend_kwargs (dict[str, Any] | None, optional): Additional keyword arguments for the
            legend plotting function. Defaults to None.
        **kwargs (Any): Additional keyword arguments for the folium map.

    Returns:
        folium.Map: Folium map with the bivariate colormap applied.

    Examples:
        Plot NYC bike trips with morning starts and ends:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import explore_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> explore_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="morning_ends",
        ... )
        <folium.folium.Map object at 0x...>

        Plot in dark mode with different colormap and different binning:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import explore_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> explore_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="morning_ends",
        ...     column_a_label="Morning Starts",
        ...     column_b_label="Morning Ends",
        ...     dark_mode=True,
        ...     cmap="bubblegum",
        ...     scheme="Quantiles",
        ...     k=10,
        ... )
        <folium.folium.Map object at 0x...>

        Plot without binning (numerical values) and different legend position:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import explore_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> explore_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="afternoon_starts",
        ...     scheme=False,
        ...     legend_loc="tr",
        ...     legend_size_px=300,
        ... )
        <folium.folium.Map object at 0x...>
    """
    # alpha - yes / no - allow iterable as list of floats between 0 and 1

    for column in (column_a, column_b):
        if isinstance(column, str) and column not in gdf.columns:
            raise ValueError(f"Column '{column}' not found in GeoDataFrame.")

    original_values_a = gdf[column_a] if isinstance(column_a, str) else column_a
    original_values_b = gdf[column_b] if isinstance(column_b, str) else column_b

    values_a, values_b = _validate_values(original_values_a, original_values_b)

    # If tiles are not defined - set based on dark mode
    if tiles is None:
        if dark_mode is None:
            dark_mode = False

        tiles = _get_default_tiles(dark_mode, kwargs)
    # If tiles are defined, set dark mode based on tiles if not defined
    elif dark_mode is None:
        dark_mode = False
        tiles_name = ""
        if isinstance(tiles, str):
            tiles_name = tiles.lower()
        elif hasattr(tiles, "name"):
            tiles_name = str(tiles.name).lower()

        for keyword in DARK_MODE_TILES_KEYWORDS:
            if keyword in tiles_name:
                dark_mode = True
                break

    set_alpha = alpha  # now its bool, but can be a list of values, then check if not empty

    if set_alpha:
        alpha_values = prepare_alpha_values(
            values_a=values_a, values_b=values_b, alpha_norm_quantile=alpha_norm_quantile
        ).tolist()

        if "style_kwds" not in kwargs:
            kwargs["style_kwds"] = {}

        kwargs["style_kwds"]["style_function"] = lambda x: dict(
            opacity=0, fillOpacity=alpha_values[int(x["id"])]
        )

    scheme_result = apply_mapclassify(values_a=values_a, values_b=values_b, scheme=scheme, k=k)

    cmap = get_bivariate_cmap(cmap)

    values_cmap = cmap(
        values_a=scheme_result.values_a,
        values_b=scheme_result.values_b,
        normalize=True,
        dark_mode=dark_mode,
    )

    hex_values = [rgb2hex(tuple(values_cmap[i, :])) for i in range(values_cmap.shape[0])]

    if "legend" in kwargs:
        kwargs.pop("legend")

    if "embed" in kwargs:
        kwargs.pop("embed")
        warnings.warn(
            "Embed folium parameter must be set to true. Ignoring user definition.", stacklevel=0
        )

    m = gdf.explore(
        color=hex_values,
        legend=False,
        tiles=tiles,
        embed=True,
        **kwargs,
    )

    if legend:
        try:
            from bivario.folium._legend import FloatBivariateMatplotlibLegend
        except (ImportError, ModuleNotFoundError) as ex:
            raise ImportError(
                "The 'folium>=0.12' package "
                "is required for showing legend. You can install it using "
                "'conda install -c conda-forge \"folium>=0.12\"' "
                "or 'pip install \"folium>=0.12\"'."
            ) from ex

        legend_kwargs = legend_kwargs or {}

        grid_size: int | tuple[int, int]
        numerical_grid_size = legend_max_grid_size or legend_size_px
        if scheme_result.scheme_a is scheme_result.scheme_b is None:
            grid_size = numerical_grid_size
        else:
            grid_size_y = (
                numerical_grid_size if scheme_result.scheme_a is None else scheme_result.k_a
            )
            grid_size_x = (
                numerical_grid_size if scheme_result.scheme_b is None else scheme_result.k_b
            )
            grid_size = (grid_size_x, grid_size_y)

        ax = plot_bivariate_legend(
            values_a=original_values_a,
            values_b=original_values_b,
            cmap=cmap,
            label_a=column_a_label,
            label_b=column_b_label,
            tick_labels_a=scheme_result.tick_labels_a,
            tick_labels_b=scheme_result.tick_labels_b,
            font_colour="#333" if legend_background else None,
            grid_size=grid_size,
            dark_mode=dark_mode,
            **legend_kwargs,
        )

        fig = cast("Figure", ax.figure)

        FloatBivariateMatplotlibLegend(
            fig=fig,
            ax=ax,
            legend_size_px=legend_size_px,
            legend_loc=legend_loc,
            legend_offset_px=legend_offset_px,
            legend_background=legend_background,
            legend_border=legend_border,
            padding_top_right_corner=scheme is not None,
        ).add_to(m)

    return m

get_bivariate_cmap

get_bivariate_cmap(cmap: str | BivariateColourmap | None = None, **kwargs: Any) -> BivariateColourmap

Return a BivariateColourmap object.

Parameters:

Name Type Description Default
cmap str | BivariateColourmap | None

Colourmap name or object. If None, will load defalt named palette - rosewood_pine. Defaults to None.

None
**kwargs Any

Additional keyword arguments for the NamedBivariateColourmap.

{}

Raises:

Type Description
TypeError

If provided cmap object is of unknown type.

Returns:

Name Type Description
BivariateColourmap BivariateColourmap

Parsed BivariateColourmap object.

Source code in bivario/cmap.py
def get_bivariate_cmap(
    cmap: str | BivariateColourmap | None = None, **kwargs: Any
) -> BivariateColourmap:
    """
    Return a BivariateColourmap object.

    Args:
        cmap (str | BivariateColourmap | None, optional): Colourmap name or object.
            If None, will load defalt named palette - rosewood_pine. Defaults to None.
        **kwargs (Any): Additional keyword arguments for the NamedBivariateColourmap.

    Raises:
        TypeError: If provided cmap object is of unknown type.

    Returns:
        BivariateColourmap: Parsed BivariateColourmap object.
    """
    # get the default color map
    if cmap is None:
        cmap = "rosewood_pine"

    # if the user passed in a BivariateColourmap, simply return it
    if isinstance(cmap, BivariateColourmap):
        return cmap
    if isinstance(cmap, str):
        return NamedBivariateColourmap(cmap, **kwargs)

    raise TypeError(
        "get_bivariate_cmap expects None or an instance of a str or BivariateColourmap. "
        f"you passed {cmap!r} of type {type(cmap)}"
    )

plot_bivariate_legend

plot_bivariate_legend(values_a: ValueInput, values_b: ValueInput, ax: Axes | None = None, cmap: BivariateColourmap | str | None = None, grid_size: int | tuple[int, int] | None = None, label_a: str | None = None, label_b: str | None = None, tick_labels_a: list[Any] | None = None, tick_labels_b: list[Any] | None = None, dark_mode: bool = False, font_colour: str | None = None, tick_fontsize_px: int = 10) -> Axes

Plot bivariate 2D legend using Matplotlib.

Generates a 2D matrix of values and uses imshow function to display it.

Parameters:

Name Type Description Default
values_a ValueInput

List or array of values for first variable. Will be assigned to the Y axis.

required
values_b ValueInput

List or array of values for second variable. Will be assigned to the X axis.

required
ax Axes | None

Matplotlib axis to plot legend on. If None, will be created. Defaults to None.

None
cmap BivariateColourmap | str | None

Bivariate colourmap to use. If None, will load a default one. Defaults to None.

None
grid_size int | tuple[int, int] | None

Number of pixels in the legend grid. Can define two different values for X and Y axis (in this order). If None, will default to 100. Defaults to None.

None
label_a str | None

Label to use for the first variable (Y axis). If None, will try to read series name, or defaults to "Value A". Defaults to None.

None
label_b str | None

Label to use for the first variable (X axis). If None, will try to read series name, or defaults to "Value B". Defaults to None.

None
tick_labels_a list[Any] | None

List of predefined ticks to use for the first variable (Y axis). Useful if binning has been applied. Defaults to None.

None
tick_labels_b list[Any] | None

List of predefined ticks to use for the first variable (X axis). Useful if binning has been applied. Defaults to None.

None
dark_mode bool

Whether to use dark mode to select a proper order of colours in the colourmap. Defaults to False.

False
font_colour str | None

Font colour for the labels and ticks. If None, will be selected based on dark_mode value - white or black. Defaults to None.

None
tick_fontsize_px int

Size of the ticksize and labels font in pixels. Defaults to 10.

10

Returns:

Name Type Description
Axes Axes

Matplotlib axes with plotted legend.

Source code in bivario/legend.py
def plot_bivariate_legend(
    values_a: "ValueInput",
    values_b: "ValueInput",
    ax: Axes | None = None,
    cmap: BivariateColourmap | str | None = None,
    grid_size: int | tuple[int, int] | None = None,
    label_a: str | None = None,
    label_b: str | None = None,
    tick_labels_a: list[Any] | None = None,
    tick_labels_b: list[Any] | None = None,
    dark_mode: bool = False,
    font_colour: str | None = None,
    tick_fontsize_px: int = 10,
) -> Axes:
    """
    Plot bivariate 2D legend using Matplotlib.

    Generates a 2D matrix of values and uses imshow function to display it.

    Args:
        values_a (ValueInput): List or array of values for first variable.
            Will be assigned to the Y axis.
        values_b (ValueInput): List or array of values for second variable.
            Will be assigned to the X axis.
        ax (Axes | None, optional): Matplotlib axis to plot legend on. If None, will be created.
            Defaults to None.
        cmap (BivariateColourmap | str | None, optional): Bivariate colourmap to use.
            If None, will load a default one. Defaults to None.
        grid_size (int | tuple[int, int] | None, optional): Number of pixels in the legend grid.
            Can define two different values for X and Y axis (in this order).
            If None, will default to 100. Defaults to None.
        label_a (str | None, optional): Label to use for the first variable (Y axis).
            If None, will try to read series name, or defaults to "Value A".
            Defaults to None.
        label_b (str | None, optional): Label to use for the first variable (X axis).
            If None, will try to read series name, or defaults to "Value B".
            Defaults to None.
        tick_labels_a (list[Any] | None, optional): List of predefined ticks to use for the first
            variable (Y axis). Useful if binning has been applied. Defaults to None.
        tick_labels_b (list[Any] | None, optional): List of predefined ticks to use for the first
            variable (X axis). Useful if binning has been applied. Defaults to None.
        dark_mode (bool, optional): Whether to use dark mode to select a proper order of colours in
            the colourmap. Defaults to False.
        font_colour (str | None, optional): Font colour for the labels and ticks. If None, will be
            selected based on dark_mode value - white or black. Defaults to None.
        tick_fontsize_px (int, optional): Size of the ticksize and labels font in pixels.
            Defaults to 10.

    Returns:
        Axes: Matplotlib axes with plotted legend.
    """
    if ax is None:
        _, ax = plt.subplots(figsize=(8, 8), dpi=DPI, layout="compressed")

    parsed_values_a, parsed_values_b = _validate_values(values_a, values_b)

    label_a = label_a or _try_parse_label(values_a) or "Value A"
    label_b = label_b or _try_parse_label(values_b) or "Value B"

    if isinstance(grid_size, (tuple, list)):
        grid_size_x, grid_size_y = grid_size
    else:
        grid_size_x = grid_size_y = grid_size or 100

    xx, yy = np.mgrid[0:grid_size_y, 0:grid_size_x]

    cmap = get_bivariate_cmap(cmap)

    legend_cmap = cmap(values_a=xx, values_b=yy, normalize=True, dark_mode=dark_mode)

    img = Image.fromarray(np.uint8((legend_cmap) * 255))

    tick_fontsize_pt = tick_fontsize_px * 72 / ax.figure.dpi

    colour = font_colour or ("white" if dark_mode else "black")
    _set_colour_theme(ax, colour)
    if tick_labels_a is None:
        y_min = float(parsed_values_a.min())
        y_max = nonsingular(y_min, float(parsed_values_a.max()), expander=1)[1]
    else:
        y_min = 0
        y_max = legend_cmap.shape[0]

    if tick_labels_b is None:
        x_min = float(parsed_values_b.min())
        x_max = nonsingular(x_min, float(parsed_values_b.max()), expander=1)[1]
    else:
        x_min = 0
        x_max = legend_cmap.shape[1]

    height_range = y_max - y_min
    width_range = x_max - x_min
    aspect = width_range / height_range

    ax.imshow(
        img,
        origin="lower",
        extent=(x_min, x_max, y_min, y_max),
        aspect=aspect,
        interpolation="nearest",
    )
    ax.tick_params(axis="both", which="both", length=0)

    ax.annotate(
        "",
        xy=(0, 1),
        xytext=(0, 0),
        arrowprops=dict(
            arrowstyle="->",
            lw=1,
            color=colour,
            shrinkA=0,
            shrinkB=0,
        ),
        xycoords="axes fraction",
    )
    ax.annotate(
        "",
        xy=(1, 0),
        xytext=(0, 0),
        arrowprops=dict(
            arrowstyle="->",
            lw=1,
            color=colour,
            shrinkA=0,
            shrinkB=0,
        ),
        xycoords="axes fraction",
    )

    ax.set_ylabel(label_a, fontsize=tick_fontsize_pt)
    ax.set_xlabel(label_b, fontsize=tick_fontsize_pt)
    ax.tick_params(labelsize=tick_fontsize_pt)

    if tick_labels_a:
        yticks = np.linspace(0, legend_cmap.shape[0], len(tick_labels_a))
        ax.set_yticks(yticks)
        ax.set_yticklabels(tick_labels_a)

    if tick_labels_b:
        xticks = np.linspace(0, legend_cmap.shape[1], len(tick_labels_b))
        ax.set_xticks(xticks)
        ax.set_xticklabels(tick_labels_b)
        auto_rotate_xticks(ax)

    return ax

viz_bivariate_data

viz_bivariate_data(data: Any | list[Any] | tuple[Any, ...], column_a: str | ValueInput, column_b: str | ValueInput, column_a_label: str | None = None, column_b_label: str | None = None, scheme: SCHEME_TYPE | tuple[SCHEME_TYPE, SCHEME_TYPE] = True, k: int | tuple[int, int] = 5, tiles: str | None = None, cmap: BivariateColourmap | str | None = None, dark_mode: bool | None = None, alpha: bool = True, alpha_norm_quantile: float = 0.9, legend: Literal[True] = True, legend_size_px: int = 400, legend_max_grid_size: int | None = 100, legend_tick_fontsize_px: int = 16, legend_kwargs: dict[str, Any] | None = None, scatterplot_kwargs: ScatterplotLayerKwargs | None = None, path_kwargs: PathLayerKwargs | None = None, polygon_kwargs: PolygonLayerKwargs | None = None, map_kwargs: MapKwargs | None = None) -> LonboardMapWithLegend
viz_bivariate_data(data: Any | list[Any] | tuple[Any, ...], column_a: str | ValueInput, column_b: str | ValueInput, column_a_label: str | None = None, column_b_label: str | None = None, scheme: SCHEME_TYPE | tuple[SCHEME_TYPE, SCHEME_TYPE] = True, k: int | tuple[int, int] = 5, tiles: str | None = None, cmap: BivariateColourmap | str | None = None, dark_mode: bool | None = None, alpha: bool = True, alpha_norm_quantile: float = 0.9, legend: Literal[False] = False, legend_size_px: int = 400, legend_max_grid_size: int | None = 100, legend_tick_fontsize_px: int = 16, legend_kwargs: dict[str, Any] | None = None, scatterplot_kwargs: ScatterplotLayerKwargs | None = None, path_kwargs: PathLayerKwargs | None = None, polygon_kwargs: PolygonLayerKwargs | None = None, map_kwargs: MapKwargs | None = None) -> Map
viz_bivariate_data(data: Any | list[Any] | tuple[Any, ...], column_a: str | ValueInput, column_b: str | ValueInput, column_a_label: str | None = None, column_b_label: str | None = None, scheme: SCHEME_TYPE | tuple[SCHEME_TYPE, SCHEME_TYPE] = True, k: int | tuple[int, int] = 5, tiles: str | None = None, cmap: BivariateColourmap | str | None = None, dark_mode: bool | None = None, alpha: bool = True, alpha_norm_quantile: float = 0.9, legend: bool = True, legend_size_px: int = 400, legend_max_grid_size: int | None = 100, legend_tick_fontsize_px: int = 16, legend_kwargs: dict[str, Any] | None = None, scatterplot_kwargs: ScatterplotLayerKwargs | None = None, path_kwargs: PathLayerKwargs | None = None, polygon_kwargs: PolygonLayerKwargs | None = None, map_kwargs: MapKwargs | None = None) -> Map | LonboardMapWithLegend

Visualize geospatial data with a bivariate colormap on a lonboard map.

Parameters:

Name Type Description Default
data Any | list[Any] | tuple[Any, ...]

Geospatial data to plot. Any compatible with lonboard viz function.

required
column_a str | ValueInput

Column name for the first variable or list/array of values.

required
column_b str | ValueInput

Column name for the second variable or list/array of values.

required
column_a_label str | None

Label for column a. If None, will use column name. Defaults to None.

None
column_b_label str | None

Label for column b. If None, will use column name. Defaults to None.

None
scheme str | None | bool | tuple

Mapclassify binning scheme for the data. If True, uses "NaturalBreaks". If False, no binning is applied. If str, uses the specified scheme. If None, no binning is applied. Can also define two different values for columns a and b. Defaults to True.

True
k int | tuple[int, int]

Number of classes for binning. Can also define two different values for columns a and b. Defaults to 5.

5
tiles str | None

Tile layer for the map. If None, will set based on dark mode - OpenFreeMap's "Dark" for the dark mode, and "Positron" for the light mode. Defaults to None.

None
cmap BivariateColourmap | str | None

Bivariate colourmap to use. If None, will load a default one. Defaults to None.

None
dark_mode bool | None

Whether to use dark mode for the map tiles. If None, will infer from the tiles if provided, otherwise defaults to False. Defaults to None

None
alpha bool

Whether to apply alpha transparency based on the data values. Will set higher values to be more opaque. It is calculated based on the normalized values of both columns. Defaults to True.

True
alpha_norm_quantile float

Quantile for normalizing alpha transparency. Will be used to calculate the maximum value for alpha scaling. It is recommended to use value below 1 to avoid outliers affecting the transparency too much. Defaults to 0.9.

0.9
legend bool

Whether to return a lonboard map with a legend plotting function. If True, will return LonboardMapWithLegend object with lonboard map and legend function. If False, will return lonboard.Map. Defaults to True.

True
legend_size_px int

Size of the legend in pixels. Defaults to 400.

400
legend_max_grid_size int | None

Max size of the legend grid used for plotting the legend. Used with scheme=False. Defaults to 100.

100
legend_tick_fontsize_px int

Size of the ticks and labels for the legend in pixels. Defaults to 16.

16
legend_kwargs dict[str, Any] | None

Additional keyword arguments for the legend plotting function. Defaults to None.

None
scatterplot_kwargs ScatterplotLayerKwargs | None

a dict of parameters to pass down to all generated lonboard.ScatterplotLayers.

None
path_kwargs PathLayerKwargs | None

a dict of parameters to pass down to all generated lonboard.PathLayers.

None
polygon_kwargs PolygonLayerKwargs | None

a dict of parameters to pass down to all generated lonboard.PolygonLayers.

None
map_kwargs MapKwargs | None

a dict of parameters to pass down to the generated lonboard.Map.

None

Returns:

Type Description
Map | LonboardMapWithLegend

lonboard.Map | LonboardMapWithLegend: Lonboard map with the bivariate colormap applied or object with lonboard map and legend plotting function.

Examples:

Plot NYC bike trips with morning starts and ends:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import viz_bivariate_data
>>> gdf = nyc_bike_trips()
>>> x = viz_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="morning_ends",
... )
>>> x
LonboardMapWithLegend(...)

Display a legend in another cell:

>>> x.legend()
<Axes: xlabel='morning_ends', ylabel='morning_starts'>

Get lonboard.Map object from the result:

>>> x.m
<lonboard._map.Map object at 0x...>

Plot in dark mode with different colormap and different binning:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import viz_bivariate_data
>>> gdf = nyc_bike_trips()
>>> viz_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="morning_ends",
...     column_a_label="Morning Starts",
...     column_b_label="Morning Ends",
...     dark_mode=True,
...     cmap="bubblegum",
...     scheme="Quantiles",
...     k=10,
... )
LonboardMapWithLegend(...)

Plot without binning (numerical values) and add tooltip to map:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import viz_bivariate_data
>>> gdf = nyc_bike_trips()
>>> viz_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="afternoon_starts",
...     scheme=False,
...     map_kwargs={"show_tooltip": True},
... )
LonboardMapWithLegend(...)

Plot without legend and get lonboard Map directly:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import viz_bivariate_data
>>> gdf = nyc_bike_trips()
>>> viz_bivariate_data(
...     gdf,
...     column_a="morning_starts",
...     column_b="morning_ends",
...     legend=False,
... )
<lonboard._map.Map object at 0x...>
Source code in bivario/lonboard/__init__.py
def viz_bivariate_data(
    data: "Any | list[Any] | tuple[Any, ...]",
    column_a: "str | ValueInput",
    column_b: "str | ValueInput",
    column_a_label: str | None = None,
    column_b_label: str | None = None,
    scheme: SCHEME_TYPE | tuple[SCHEME_TYPE, SCHEME_TYPE] = True,
    k: int | tuple[int, int] = 5,
    tiles: str | None = None,
    cmap: BivariateColourmap | str | None = None,
    dark_mode: bool | None = None,
    alpha: bool = True,
    alpha_norm_quantile: float = 0.9,
    legend: bool = True,
    legend_size_px: int = 400,
    legend_max_grid_size: int | None = 100,
    legend_tick_fontsize_px: int = 16,
    legend_kwargs: dict[str, Any] | None = None,
    scatterplot_kwargs: "ScatterplotLayerKwargs | None" = None,
    path_kwargs: "PathLayerKwargs | None" = None,
    polygon_kwargs: "PolygonLayerKwargs | None" = None,
    map_kwargs: "MapKwargs | None" = None,
) -> "Map | LonboardMapWithLegend":
    """
    Visualize geospatial data with a bivariate colormap on a lonboard map.

    Args:
        data (Any | list[Any] | tuple[Any, ...]): Geospatial data to plot. Any compatible with
            lonboard viz function.
        column_a (str | ValueInput): Column name for the first variable or list/array of values.
        column_b (str | ValueInput): Column name for the second variable or list/array of values.
        column_a_label (str | None, optional): Label for column a. If None, will use column name.
            Defaults to None.
        column_b_label (str | None, optional): Label for column b. If None, will use column name.
            Defaults to None.
        scheme (str | None | bool | tuple, optional): Mapclassify binning scheme for the data.
            If True, uses "NaturalBreaks". If False, no binning is applied.
            If str, uses the specified scheme. If None, no binning is applied. Can also define
            two different values for columns a and b. Defaults to True.
        k (int | tuple[int, int], optional): Number of classes for binning. Can also define two
            different values for columns a and b. Defaults to 5.
        tiles (str | None, optional): Tile layer for the map. If None, will set based
            on dark mode - OpenFreeMap's "Dark" for the dark mode, and "Positron"
            for the light mode. Defaults to None.
        cmap (BivariateColourmap | str | None, optional): Bivariate colourmap to use.
            If None, will load a default one. Defaults to None.
        dark_mode (bool | None, optional): Whether to use dark mode for the map tiles. If None,
            will infer from the tiles if provided, otherwise defaults to False. Defaults to None
        alpha (bool, optional): Whether to apply alpha transparency based on the data values. Will
            set higher values to be more opaque. It is calculated based on the normalized values of
            both columns. Defaults to True.
        alpha_norm_quantile (float, optional): Quantile for normalizing alpha transparency.
            Will be used to calculate the maximum value for alpha scaling. It is recommended to use
            value below 1 to avoid outliers affecting the transparency too much. Defaults to 0.9.
        legend (bool, optional): Whether to return a lonboard map with a legend plotting function.
            If True, will return LonboardMapWithLegend object with lonboard map and legend function.
            If False, will return lonboard.Map. Defaults to True.
        legend_size_px (int, optional): Size of the legend in pixels. Defaults to 400.
        legend_max_grid_size (int | None, optional): Max size of the legend grid used for plotting
            the legend. Used with scheme=False. Defaults to 100.
        legend_tick_fontsize_px (int, optional): Size of the ticks and labels for the legend
            in pixels. Defaults to 16.
        legend_kwargs (dict[str, Any] | None, optional): Additional keyword arguments for the
            legend plotting function. Defaults to None.
        scatterplot_kwargs: a `dict` of parameters to pass down to all generated
            lonboard.ScatterplotLayers.
        path_kwargs: a `dict` of parameters to pass down to all generated
            lonboard.PathLayers.
        polygon_kwargs: a `dict` of parameters to pass down to all generated
            lonboard.PolygonLayers.
        map_kwargs: a `dict` of parameters to pass down to the generated
            lonboard.Map.

    Returns:
        lonboard.Map | LonboardMapWithLegend: Lonboard map with the bivariate colormap applied or
            object with lonboard map and legend plotting function.

    Examples:
        Plot NYC bike trips with morning starts and ends:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import viz_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> x = viz_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="morning_ends",
        ... )
        >>> x
        LonboardMapWithLegend(...)

        Display a legend in another cell:
        >>> x.legend()
        <Axes: xlabel='morning_ends', ylabel='morning_starts'>

        Get lonboard.Map object from the result:
        >>> x.m
        <lonboard._map.Map object at 0x...>

        Plot in dark mode with different colormap and different binning:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import viz_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> viz_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="morning_ends",
        ...     column_a_label="Morning Starts",
        ...     column_b_label="Morning Ends",
        ...     dark_mode=True,
        ...     cmap="bubblegum",
        ...     scheme="Quantiles",
        ...     k=10,
        ... )
        LonboardMapWithLegend(...)

        Plot without binning (numerical values) and add tooltip to map:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import viz_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> viz_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="afternoon_starts",
        ...     scheme=False,
        ...     map_kwargs={"show_tooltip": True},
        ... )
        LonboardMapWithLegend(...)

        Plot without legend and get lonboard Map directly:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import viz_bivariate_data
        >>> gdf = nyc_bike_trips()
        >>> viz_bivariate_data(
        ...     gdf,
        ...     column_a="morning_starts",
        ...     column_b="morning_ends",
        ...     legend=False,
        ... )
        <lonboard._map.Map object at 0x...>
    """
    try:
        from lonboard import viz
    except (ImportError, ModuleNotFoundError) as ex:
        raise ImportError(
            "The 'lonboard>=0.10' package "
            "is required for plotting lonboard map. You can install it using "
            "'conda install -c conda-forge \"lonboard>=0.10\"' "
            "or 'pip install \"lonboard>=0.10\"'."
        ) from ex

    narwhals_df = None

    if isinstance(column_a, str) or isinstance(column_b, str):
        try:
            cols_to_select = []
            if isinstance(column_a, str):
                cols_to_select.append(column_a)
            if isinstance(column_b, str):
                cols_to_select.append(column_b)

            narwhals_df = nw.from_native(cast("IntoFrame", data)).select(*cols_to_select)

            if isinstance(narwhals_df, nw.LazyFrame):
                narwhals_df = narwhals_df.collect()

            original_values_a = narwhals_df[column_a] if isinstance(column_a, str) else column_a
            original_values_b = narwhals_df[column_b] if isinstance(column_b, str) else column_b
        except TypeError as ex:
            raise TypeError(
                "Cannot parse provided input as a source for loading str column."
            ) from ex
    else:
        original_values_a = column_a
        original_values_b = column_b

    values_a, values_b = _validate_values(original_values_a, original_values_b)

    # If tiles are not defined - set based on dark mode
    if tiles is None:
        if dark_mode is None:
            dark_mode = False

        tiles = DARK_STYLE if dark_mode else LIGHT_STYLE
    # If tiles are defined, set dark mode based on tiles if not defined
    elif dark_mode is None:
        dark_mode = False
        tiles_name = tiles.lower()

        for keyword in DARK_MODE_TILES_KEYWORDS:
            if keyword in tiles_name:
                dark_mode = True
                break

    set_alpha = alpha  # now its bool, but can be a list of values, then check if not empty

    alpha_values = None

    if set_alpha:
        alpha_values = prepare_alpha_values(
            values_a=values_a, values_b=values_b, alpha_norm_quantile=alpha_norm_quantile
        ).reshape(-1, 1)

    scheme_result = apply_mapclassify(values_a=values_a, values_b=values_b, scheme=scheme, k=k)

    cmap = get_bivariate_cmap(cmap)

    values_cmap = cmap(
        values_a=scheme_result.values_a,
        values_b=scheme_result.values_b,
        normalize=True,
        dark_mode=dark_mode,
    )

    if alpha_values is not None:
        values_cmap = np.concatenate([values_cmap, alpha_values], axis=1)

    values_cmap = (values_cmap * 255).astype(np.uint8)

    map_kwargs = map_kwargs or {}
    polygon_kwargs = polygon_kwargs or {}
    scatterplot_kwargs = scatterplot_kwargs or {}
    path_kwargs = path_kwargs or {}

    try:
        from lonboard.basemap import MaplibreBasemap

        map_kwargs["basemap"] = MaplibreBasemap(style=tiles)
    except ImportError:  # lonboard<0.13
        map_kwargs["basemap_style"] = tiles

    # Polygon layer
    polygon_kwargs["filled"] = True
    polygon_kwargs["get_fill_color"] = values_cmap

    if "stroked" not in polygon_kwargs:
        polygon_kwargs["stroked"] = False
    if "opacity" not in polygon_kwargs:
        polygon_kwargs["opacity"] = 1

    # Scatterplot layer
    scatterplot_kwargs["filled"] = True
    scatterplot_kwargs["get_fill_color"] = values_cmap

    if "stroked" not in scatterplot_kwargs:
        scatterplot_kwargs["stroked"] = False
    if "opacity" not in scatterplot_kwargs:
        scatterplot_kwargs["opacity"] = 1

    # Path layer
    path_kwargs["get_color"] = values_cmap

    if "opacity" not in path_kwargs:
        path_kwargs["opacity"] = 1

    m = viz(
        data=data,
        map_kwargs=map_kwargs,
        polygon_kwargs=polygon_kwargs,
        scatterplot_kwargs=scatterplot_kwargs,
        path_kwargs=path_kwargs,
    )

    if legend:
        legend_kwargs = legend_kwargs or {}

        grid_size: int | tuple[int, int]
        numerical_grid_size = legend_max_grid_size or legend_size_px
        if scheme_result.scheme_a is scheme_result.scheme_b is None:
            grid_size = numerical_grid_size
        else:
            grid_size_y = (
                numerical_grid_size if scheme_result.scheme_a is None else scheme_result.k_a
            )
            grid_size_x = (
                numerical_grid_size if scheme_result.scheme_b is None else scheme_result.k_b
            )
            grid_size = (grid_size_x, grid_size_y)

        def display_legend() -> "Axes":
            ax = plot_bivariate_legend(
                values_a=original_values_a,
                values_b=original_values_b,
                cmap=cmap,
                label_a=column_a_label,
                label_b=column_b_label,
                tick_labels_a=scheme_result.tick_labels_a,
                tick_labels_b=scheme_result.tick_labels_b,
                font_colour="black",
                grid_size=grid_size,
                dark_mode=dark_mode,
                tick_fontsize_px=legend_tick_fontsize_px,
                **legend_kwargs,
            )
            fig = cast("Figure", ax.figure)
            resize_fig(fig=fig, ax=ax, legend_size_px=legend_size_px)
            # plt.show()

            return ax

        return LonboardMapWithLegend(m=m, legend=display_legend)

    return m

Example data

Example datasets for bivario package.

nyc_bike_trips

nyc_bike_trips() -> GeoDataFrame

Load example NYC bike trips data as a GeoDataFrame.

Contains H3-indexed bike trip start and end locations in New York City. Starts and split into morning and afternoon trips.

Available columns
  • h3: H3 index of the location
  • morning_starts: Number of bike trips starting in the morning
  • morning_ends: Number of bike trips ending in the morning
  • afternoon_starts: Number of bike trips starting in the afternoon
  • afternoon_ends: Number of bike trips ending in the afternoon
  • geometry: Geometry of the H3 cell

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: A GeoDataFrame containing NYC bike trips data.

Examples:

Plot example folium map with this data:

>>> from bivario.example_data import nyc_bike_trips
>>> from bivario import explore_bivariate_data
>>> explore_bivariate_data(
...     nyc_bike_trips(),
...     column_a="morning_starts",
...     column_b="morning_ends",
... )
<folium.folium.Map object at 0x...>
Source code in bivario/example_data/__init__.py
def nyc_bike_trips() -> "gpd.GeoDataFrame":
    """
    Load example NYC bike trips data as a GeoDataFrame.

    Contains H3-indexed bike trip start and end locations in New York City.
    Starts and split into morning and afternoon trips.

    Available columns:
        - h3: H3 index of the location
        - morning_starts: Number of bike trips starting in the morning
        - morning_ends: Number of bike trips ending in the morning
        - afternoon_starts: Number of bike trips starting in the afternoon
        - afternoon_ends: Number of bike trips ending in the afternoon
        - geometry: Geometry of the H3 cell

    Returns:
        gpd.GeoDataFrame: A GeoDataFrame containing NYC bike trips data.

    Examples:
        Plot example folium map with this data:
        >>> from bivario.example_data import nyc_bike_trips
        >>> from bivario import explore_bivariate_data
        >>> explore_bivariate_data(
        ...     nyc_bike_trips(),
        ...     column_a="morning_starts",
        ...     column_b="morning_ends",
        ... )
        <folium.folium.Map object at 0x...>
    """
    try:
        import geopandas as gpd
    except (ImportError, ModuleNotFoundError) as ex:
        raise ImportError(
            "The 'geopandas' package "
            "is required for loading example data. You can install it using "
            "'conda install -c conda-forge geopandas' "
            "or 'pip install geopandas'."
        ) from ex

    data_path = Path(__file__).parent / "nyc_bike_trips.csv.gz"
    df = gpd.pd.read_csv(data_path)
    gdf = gpd.GeoDataFrame(df, geometry=gpd.GeoSeries.from_wkt(df["geometry"], crs=4326))
    return gdf