Skip to content

Open in Colab

Bivario with Matplotlib

image.png

Below is an examples of how to plot the geo data with matptotlib using geopandas.GeoDataFrame.plot() function.

Basemaps are drawn with basemaplibre, which requires Python 3.11 or newer.

import basemaplibre as bml
import matplotlib.pyplot as plt

from bivario import get_bivariate_cmap
from bivario._alpha import prepare_alpha_values
from bivario._scheme import apply_mapclassify
from bivario.example_data import nyc_bike_trips
from bivario.legend import plot_bivariate_legend

Load the data

We will use example data from the library representing NYC Bike trips aggregated per H3 cells.

gdf = nyc_bike_trips()
gdf
h3 morning_starts morning_ends afternoon_starts afternoon_ends geometry
0 617733120577503231 903 440 760 803 POLYGON ((-73.88768 40.876, -73.88979 40.87506...
1 617733120577765375 908 342 1259 1695 POLYGON ((-73.88544 40.87341, -73.88755 40.872...
2 617733120578027519 366 860 1180 775 POLYGON ((-73.89196 40.87589, -73.89408 40.874...
3 617733120578289663 1848 1338 2768 2401 POLYGON ((-73.88972 40.8733, -73.89183 40.8723...
4 617733120578551807 1387 759 2208 2456 POLYGON ((-73.88563 40.8787, -73.88774 40.8777...
... ... ... ... ... ... ...
1564 617733152329433087 1239 925 1121 1310 POLYGON ((-74.00425 40.67719, -74.00635 40.676...
1565 617733152329695231 1770 2077 3805 3374 POLYGON ((-74.00201 40.67461, -74.00411 40.673...
1566 617733152329957375 1544 1399 1888 2300 POLYGON ((-74.00852 40.67707, -74.01062 40.676...
1567 617733152333627391 2264 2899 8916 8258 POLYGON ((-74.01503 40.67954, -74.01713 40.678...
1568 617733152333889535 1937 2825 7320 6637 POLYGON ((-74.01279 40.67696, -74.01489 40.676...

1569 rows × 6 columns

Load and apply bivariate colourmap

We will calculate RGB values for each row and use it in the .plot() function.

cmap = get_bivariate_cmap()
colours = cmap(gdf["morning_starts"], gdf["morning_ends"])
colours
array([[ 0.97560948,  0.95003397,  0.71695376],
       [ 0.97661289,  0.95043696,  0.71739628],
       [ 0.97125424,  0.95284457,  0.71564378],
       ..., 
       [ 0.9658414 ,  0.9400308 ,  0.71184284],
       [ 0.95050117,  0.92695511,  0.70421747],
       [ 0.95125374,  0.93013836,  0.70491759]])

Basic plot with inset legend

We will plot values in raw numerical mode and plot a legend in a designated separate inset axis.

fig, ax = plt.subplots(figsize=(15, 15), dpi=200)

gdf.plot(
    color=colours,
    ax=ax,
)

gdf.boundary.plot(ax=ax, color="black", linewidth=0.5, alpha=0.1)

# Plot legend as inset axis
inset_width = 0.3
inset_height = 0.25
x0 = 0.1
y0 = 1 - inset_height
inset_pos = [x0, y0, inset_width, inset_height]

inset_coords = ax.transAxes.transform(inset_pos[:2])
inset_size = ax.transAxes.transform([inset_width, inset_height]) - ax.transAxes.transform([0, 0])
inset_fig_coords = fig.transFigure.inverted().transform(inset_coords)
inset_fig_size = fig.transFigure.inverted().transform(inset_size + inset_coords) - inset_fig_coords

legend_ax = fig.add_axes((*inset_fig_coords, *inset_fig_size))
plot_bivariate_legend(
    gdf["morning_starts"],
    gdf["morning_ends"],
    ax=legend_ax,
    cmap=cmap,
    label_a="Morning starts",
    label_b="Morning ends",
    tick_fontsize_px=24,
)

ax.set_title("NYC Bike Trips: Morning Starts vs Morning Ends")

bml.add_basemap(ax, crs=gdf.crs, source="OpenFreeMap.Positron", labels=False)

plt.show()

png

Calculate alpha values

To improve readability, we can calculate alpha values to make regions with small values in both columns be less visible.

alpha_values = prepare_alpha_values(gdf["morning_starts"], gdf["morning_ends"])
alpha_values
array([ 0.22453621,  0.22515699,  0.22112535, ...,  0.29360683,
        0.4059882 ,  0.40077307])

Apply mapclassify scheme

To make the colours more readable for the user, we can apply mapclassify to bin values together.

By default, the values are grouped into 5 bins with NaturalBreaks algorithm.

binning_result = apply_mapclassify(gdf["morning_starts"], gdf["morning_ends"])

Recalculate the colours with new binning result

We will load another palette and set it to dark mode.

cmap = get_bivariate_cmap("glacier_ember", dark_mode=True)
binned_colours = cmap(binning_result.values_a, binning_result.values_b)

Plot grouped data in dark mode

fig, ax = plt.subplots(figsize=(15, 15), dpi=200)

gdf.plot(
    color=binned_colours,
    alpha=alpha_values,
    ax=ax,
)

gdf.boundary.plot(ax=ax, color="white", linewidth=0.5, alpha=0.1 * alpha_values)

# Plot legend as inset axis
inset_width = 0.3
inset_height = 0.25
x0 = 0.1
y0 = 1 - inset_height
inset_pos = [x0, y0, inset_width, inset_height]

inset_coords = ax.transAxes.transform(inset_pos[:2])
inset_size = ax.transAxes.transform([inset_width, inset_height]) - ax.transAxes.transform([0, 0])
inset_fig_coords = fig.transFigure.inverted().transform(inset_coords)
inset_fig_size = fig.transFigure.inverted().transform(inset_size + inset_coords) - inset_fig_coords

legend_ax = fig.add_axes((*inset_fig_coords, *inset_fig_size))
# We will use binning result values to plot the legend
grid_size_x = binning_result.k_b  # note the switch here - second variable goes to X axis
grid_size_y = binning_result.k_a  # first variable goes to Y axis

plot_bivariate_legend(
    gdf["morning_starts"],
    gdf["morning_ends"],
    ax=legend_ax,
    cmap=cmap,
    label_a="Morning starts",
    label_b="Morning ends",
    tick_labels_a=binning_result.tick_labels_a,
    tick_labels_b=binning_result.tick_labels_b,
    grid_size=(grid_size_x, grid_size_y),
    tick_fontsize_px=24,
    dark_mode=True,
)

ax.set_title("NYC Bike Trips: Morning Starts vs Morning Ends")

bml.add_basemap(ax, crs=gdf.crs, source="OpenFreeMap.Dark", labels=False)

plt.show()

png

Plot legend next to map

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 15), dpi=200, width_ratios=[2, 1])

gdf.plot(
    color=binned_colours,
    alpha=alpha_values,
    ax=ax1,
)

gdf.boundary.plot(ax=ax1, color="white", linewidth=0.5, alpha=0.1 * alpha_values)

# We will use binning result values to plot the legend
grid_size_x = binning_result.k_b  # note the switch here - second variable goes to X axis
grid_size_y = binning_result.k_a  # first variable goes to Y axis

plot_bivariate_legend(
    gdf["morning_starts"],
    gdf["morning_ends"],
    ax=ax2,
    cmap=cmap,
    label_a="Morning starts",
    label_b="Morning ends",
    tick_labels_a=binning_result.tick_labels_a,
    tick_labels_b=binning_result.tick_labels_b,
    grid_size=(grid_size_x, grid_size_y),
    tick_fontsize_px=24,
    dark_mode=True,
    # we set the font colour to black to contrast with the white boundary
    # dark_mode set to True makes the font white by default
    font_colour="black",
)

ax1.set_title("NYC Bike Trips: Morning Starts vs Morning Ends")

bml.add_basemap(ax1, crs=gdf.crs, source="OpenFreeMap.Dark", labels=False)

plt.show()

png