# Marimekko and Mosaic Charts in Python

> Make a Marimekko (mekko) chart in Python with Matplotlib ax.bar and variable widths, or a mosaic plot with statsmodels mosaic, including labels and totals.

Source: https://www.pythoncharts.com/matplotlib/marimekko-mosaic-chart-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, statsmodels, marimekko chart, mosaic plot, stacked bar chart

A Marimekko chart is a 100% stacked bar chart whose bar **widths** also carry
data, so each rectangle's area is its share of the total. In Matplotlib, draw
it with `ax.bar(left_edges, heights, width=widths, align="edge", bottom=...)`.
For raw categorical records, `statsmodels.graphics.mosaicplot.mosaic()` draws a
similar mosaic plot. This post uses Matplotlib 3.11 and statsmodels 0.15.

## Quick Example

Made-up snack sales by region (width) and product type (height):

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

sales = pd.DataFrame(                       # $ millions
    {"Chips": [120, 60, 45, 20],
     "Nuts": [50, 70, 20, 12],
     "Bars": [60, 55, 15, 28],
     "Dried fruit": [20, 35, 10, 10]},
    index=["Americas", "Europe", "Asia", "Africa"])

widths = sales.sum(axis=1) / sales.values.sum() * 100
lefts = widths.cumsum() - widths
shares = sales.div(sales.sum(axis=1), axis=0) * 100
colors = ["#e07a5f", "#3d405b", "#81b29a", "#f2cc8f"]

fig, ax = plt.subplots(figsize=(9.5, 5.5))
bottom = np.zeros(len(sales))
for product, color in zip(sales.columns, colors):
    bars = ax.bar(lefts, shares[product], width=widths, bottom=bottom,
                  align="edge", color=color, edgecolor="white", lw=2,
                  label=product)
    ax.bar_label(bars, labels=[f"{v:.0f}%" for v in shares[product]],
                 label_type="center", fontsize=9,
                 color="white" if product in ("Chips", "Nuts") else "black")
    bottom += shares[product].to_numpy()

for region, left, width in zip(sales.index, lefts, widths):
    ax.text(left + width / 2, 102, f"{region}\n{width:.0f}%", ha="center",
            va="bottom", fontsize=10)

ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
ax.set_xlabel("Share of total sales (%)")
ax.set_ylabel("Share within region (%)")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(loc="upper left", bbox_to_anchor=(1.01, 1), reverse=True)
plt.show()
```

![Marimekko chart of snack sales where column width shows each region's share of total sales and stacked segments show product mix](https://www.pythoncharts.com/matplotlib/marimekko-mosaic-chart-python/images/marimekko-quick-example.png)

## How do I read a Marimekko chart?

- Column width: the region's share of all sales.
- Segment height: the product's share *within* that region.
- Rectangle area: that region and product as a share of all sales.

```python
total = sales.values.sum()
cells = (sales / total * 100).stack().sort_values(ascending=False)
print(cells.head(3).round(1))
```

```text
Americas  Chips    19.0
Europe    Nuts     11.1
Americas  Bars      9.5
dtype: float64
```

## Label rectangles with values, hiding small ones

Text in a thin or short rectangle is unreadable. Label a cell only if its area is
large enough.

```python
fig, ax = plt.subplots(figsize=(9.5, 5.5))
bottom = np.zeros(len(sales))
for product, color in zip(sales.columns, colors):
    ax.bar(lefts, shares[product], width=widths, bottom=bottom, align="edge",
           color=color, edgecolor="white", lw=2)
    for region, left, width, low, height in zip(
            sales.index, lefts, widths, bottom, shares[product]):
        if width * height / 100 >= 3:        # at least 3% of all sales
            ax.text(left + width / 2, low + height / 2,
                    f"{product}\n${sales.loc[region, product]}M",
                    ha="center", va="center", fontsize=9,
                    color="white" if product in ("Chips", "Nuts") else "black")
    bottom += shares[product].to_numpy()

ax.set_xticks(lefts + widths / 2, sales.index)
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
ax.yaxis.set_major_formatter("{x:.0f}%")
ax.tick_params(bottom=False)
plt.show()
```

![Marimekko chart with product names and dollar values inside rectangles above three percent of sales](https://www.pythoncharts.com/matplotlib/marimekko-mosaic-chart-python/images/marimekko-labels.png)

## Mosaic plot with statsmodels

`mosaic()` counts the category combinations in a DataFrame, which suits survey
or event records.

```python
from statsmodels.graphics.mosaicplot import mosaic

rng = np.random.default_rng(223)
plan = rng.choice(["Free", "Pro", "Team"], 1000, p=[0.55, 0.3, 0.15])
stay = {"Free": 0.55, "Pro": 0.78, "Team": 0.9}
status = np.where(rng.random(1000) < [stay[p] for p in plan],
                  "Retained", "Churned")
users = pd.DataFrame({"plan": plan, "status": status})

palette = {"Retained": "#457b9d", "Churned": "#e63946"}
fig, ax = plt.subplots(figsize=(8.5, 5))
mosaic(users.sort_values(["plan", "status"], ascending=[True, False]),
       ["plan", "status"], ax=ax, gap=0.012,
       properties=lambda key: {"color": palette[key[1]]},
       labelizer=lambda key: f"{key[1]}\n{((users.plan == key[0]) & (users.status == key[1])).sum()}")
plt.show()

print(pd.crosstab(users.plan, users.status, normalize="index").round(2))
```

```text
status  Churned  Retained
plan                     
Free       0.46      0.54
Pro        0.21      0.79
Team       0.08      0.92
```

![Mosaic plot of 1,000 users by plan and retention; the Free column is widest and has the largest churned share](https://www.pythoncharts.com/matplotlib/marimekko-mosaic-chart-python/images/marimekko-mosaic.png)

## Highlight surprising cells

`statistic=True` colors cells by how far they are from what you'd expect if the
two variables were unrelated. Here red cells hold more users than expected and
blue cells fewer.

```python
fig, ax = plt.subplots(figsize=(8.5, 5))
mosaic(users.sort_values(["plan", "status"]), ["plan", "status"], ax=ax,
       gap=0.012, statistic=True)
for text in ax.texts:
    text.set_color("white")          # readable on the dark fills
plt.show()
```

![Mosaic plot with red cells for combinations more common than expected, such as free users who churned, and blue cells for less common ones](https://www.pythoncharts.com/matplotlib/marimekko-mosaic-chart-python/images/marimekko-statistic.png)

Test the association with `scipy.stats.chi2_contingency()` rather than judging
shades by eye.

```python
from scipy.stats import chi2_contingency

result = chi2_contingency(pd.crosstab(users.plan, users.status))
print(f"chi2 = {result.statistic:.1f}, p = {result.pvalue:.2g}")
```

```text
chi2 = 101.6, p = 8.7e-23
```

## Marimekko or another chart?

| Data | Chart |
|---|---|
| Mix within groups, and the groups differ a lot in size | Marimekko |
| Mix only | [100% stacked bar chart](https://www.pythoncharts.com/matplotlib/stacked-bar-charts-labels/) |
| Compare absolute values precisely | [Grouped bar chart](https://www.pythoncharts.com/matplotlib/grouped-bar-charts-matplotlib/) |
| Hierarchy of parts | [Treemap](https://www.pythoncharts.com/python/matplotlib-treemap-squarify/) |

## Practical tips

- Keep to about five columns and five segments.
- Order columns by width, and put the same segment at the bottom of every column.
- Only the bottom segment shares a baseline, so give it the category you most want compared.
- Print values, since readers compare areas poorly.

## Similar Topics

- [Stacked Bar Charts with Labels in Matplotlib](https://www.pythoncharts.com/matplotlib/stacked-bar-charts-labels/)
- [Treemaps in Python with squarify](https://www.pythoncharts.com/python/matplotlib-treemap-squarify/)
- [Seaborn countplot](https://www.pythoncharts.com/seaborn/seaborn-countplot/)
