How to Apply Proportional Partitions to a Flow Cartogram¶
You can combine the flow cartogram and proportional cartogram modules to show two variables at once: the flow cartogram resizes each region by one variable, and proportional partitions subdivide each region to show a second variable.
A typical use case: resize states by total population, then split each state by party vote share.
import matplotlib.pyplot as plt
import carto_flow.data as examples
import carto_flow.flow_cartogram as flow
import carto_flow.proportional_cartogram as prop
Step 1: Create a flow cartogram¶
Start by morphing the geometries. We'll use US Census data with race/ethnicity breakdowns as our secondary variable.
gdf = examples.load_us_census(population=True, race=True)
gdf["Minorities"] = gdf["Black or African American"] + gdf["Asian"] + gdf["Hispanic or Latino"]
cartogram = flow.morph_gdf(gdf, "Minorities", options=flow.MorphOptions(grid_size=512))
cartogram_gdf = cartogram.to_geodataframe()
Morph geometries: 49%|█████████████████ | 243/500 [00:09<00:10, 24.87it/s, max=7.0%, mean=0.4% - converged]
Step 2: Apply proportional partitions¶
partition_geometries() takes the morphed GeoDataFrame and splits each geometry according to the given columns. Use normalization='row' so each region fills completely (no remainder).
race_columns = ["Black or African American", "Hispanic or Latino", "Asian"]
partitioned = prop.partition_geometries(
cartogram_gdf,
columns=race_columns,
method="split",
direction="horizontal",
strategy="treemap",
normalization="row",
treemap_reference="mean",
)
Step 3: Visualize¶
plot_partitions() colors each partition by category. The result shows both variables: region size encodes population, and the colored splits encode the race/ethnicity breakdown.
from carto_flow.proportional_cartogram.visualization import plot_partitions
fig, ax = plt.subplots(figsize=(12, 7))
palette = {"Black or African American": "indigo", "Asian": "darkorchid", "Hispanic or Latino": "plum"}
result = plot_partitions(partitioned, color_by="category", edgecolor="white", palette=palette, ax=ax)
result.legend.set_loc("lower left")
ax.set(title="Population cartogram with race/ethnicity breakdown")
plt.tight_layout();