# How to Make a Venn Diagram in Python (and When to Use an UpSet Plot)

> Make a Venn diagram in Python with venn2 and venn3 from matplotlib-venn. Style regions, show percentages, and build an UpSet plot in Matplotlib for 4+ sets.

Source: https://www.pythoncharts.com/python/venn-diagram-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: Python | Tags: python, matplotlib, venn diagram, matplotlib-venn, upset plot, sets

To make a Venn diagram in Python, install [`matplotlib-venn`](https://github.com/konstantint/matplotlib-venn) and call `venn2()` for two sets or `venn3()` for three. Pass Python sets and it counts every overlap for you.

Install it with `pip install matplotlib-venn`. The examples use version 1.1.2.

## Quick Example

This compares which customers bought through three sales channels, using sets of customer IDs.

```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib_venn import venn3

rng = np.random.default_rng(11)
customers = np.arange(2000)

web = set(rng.choice(customers, 900, replace=False))
app = set(rng.choice(customers, 600, replace=False))
store = set(rng.choice(customers, 450, replace=False))

fig, ax = plt.subplots(figsize=(7, 6))
venn3([web, app, store], set_labels=("Website", "Mobile app", "In store"),
      set_colors=("#118ab2", "#ef476f", "#ffd166"), alpha=0.6, ax=ax)
ax.set_title("Where customers shopped last quarter", fontsize=14)
plt.show()
```

![Three set Venn diagram of Website, Mobile app and In store customers, with 62 in all three and 497 on the website only](https://www.pythoncharts.com/python/venn-diagram-python/images/venn-diagram-python-quick-example.png)

Each number counts the customers in that region only. Of the 1,415 customers who appear in any set, 497 used only the website and 62 used all three channels.

With a DataFrame that has one row per purchase, build each set with a filter such as `set(df.loc[df["channel"] == "web", "customer_id"])`.

## Two Set Venn Diagram from Counts

If you already know the region sizes, pass them as `subsets` instead of sets. For `venn2()` the order is: only A, only B, both.

```python
from matplotlib_venn import venn2

fig, ax = plt.subplots(figsize=(7, 4.5))
venn2(subsets=(320, 180, 95), set_labels=("Newsletter", "Loyalty program"),
      set_colors=("#06a77d", "#7b2cbf"), alpha=0.5, ax=ax)
ax.set_title("Marketing list overlap")
plt.show()
```

![Two set Venn diagram showing 320 newsletter only, 180 loyalty program only and 95 in both](https://www.pythoncharts.com/python/venn-diagram-python/images/venn-diagram-two-sets.png)

The newsletter has 415 people in total here, because 320 is the count outside the overlap.

`venn3()` takes seven counts. A dictionary is clearer than a tuple: each key is three digits saying whether the region is in A, B, and C, so `"101"` means in A and C but not B.

## Show Percentages and Highlight a Region

`subset_label_formatter` controls the text in each region. To restyle one region, get it by the same binary ID with `get_patch_by_id()` and `get_label_by_id()`. `venn3_circles()` adds outlines.

```python
from matplotlib_venn import venn3_circles

total = len(web | app | store)
sets = [web, app, store]

fig, ax = plt.subplots(figsize=(7, 6))
v = venn3(sets, set_labels=("Website", "Mobile app", "In store"),
          set_colors=("#adb5bd",) * 3, alpha=0.35, ax=ax,
          subset_label_formatter=lambda n: f"{n}\n{n / total:.0%}")
venn3_circles(sets, linewidth=1.2, color="#343a40", ax=ax)

center = v.get_patch_by_id("111")
center.set_color("#f3722c")
center.set_alpha(1)
v.get_label_by_id("111").set_fontweight("bold")
ax.set_title("Customers who used all three channels", fontsize=14)
plt.show()
```

![Grey Venn diagram with outlined circles, counts and percentages in each region, and the center region of 62 customers, 4 percent, highlighted in orange](https://www.pythoncharts.com/python/venn-diagram-python/images/venn-diagram-styled.png)

If a region is empty, `get_patch_by_id()` and `get_label_by_id()` can return `None`, so check before calling methods on the result when your data changes.

## Equal-Sized Circles

By default, areas are scaled to the counts. That makes small regions unreadable when sizes differ a lot, and three circles often can't represent seven counts exactly. For equal regions, pass a layout algorithm with `fixed_subset_sizes`:

```python
from matplotlib_venn.layout.venn3 import DefaultLayoutAlgorithm

beta = {"100": 800, "010": 60, "001": 25, "110": 120, "101": 40, "011": 5, "111": 10}

fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
venn3(beta, set_labels=("A", "B", "C"), ax=axes[0])
axes[0].set_title("Area-weighted (default)")
equal = DefaultLayoutAlgorithm(fixed_subset_sizes=(1, 1, 1, 1, 1, 1, 1))
venn3(beta, set_labels=("A", "B", "C"), layout_algorithm=equal, ax=axes[1])
axes[1].set_title("Equal-sized regions")
plt.show()
```

![The same counts drawn twice: area-weighted circles with one very large circle and crowded small regions, and three equal circles with readable labels](https://www.pythoncharts.com/python/venn-diagram-python/images/venn-diagram-weighted-vs-unweighted.png)

Older examples use `venn3_unweighted()`, which is deprecated in 1.1.2 in favor of this approach. `venn2` has a matching `DefaultLayoutAlgorithm` in `matplotlib_venn.layout.venn2`.

## Venn Diagram with 4 or More Sets: Use an UpSet Plot

`matplotlib-venn` stops at three sets, and five sets already have 31 possible overlaps. An UpSet plot handles this with one bar per combination, and a dot grid underneath showing which sets it contains.

The [UpSetPlot](https://upsetplot.readthedocs.io/) package draws these, but its latest release (0.9.0) raised an error with pandas 3.0.5 in our testing. It imports and runs with pandas 2.x. The chart is also straightforward to build in Matplotlib from a table of True/False membership columns:

```python
import pandas as pd

rng = np.random.default_rng(8)
n = 1500
active = rng.beta(2, 2, n)  # more active customers use more channels
rates = {"Website": 0.9, "App": 0.7, "Store": 0.55, "Phone": 0.25, "Social": 0.35}
used = pd.DataFrame({name: rng.random(n) < rate * active for name, rate in rates.items()})

combos = used[used.any(axis=1)].value_counts().head(15)
names = list(used.columns)
x = np.arange(len(combos))
y = np.arange(len(names))

fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharex="col", sharey="row",
                         gridspec_kw={"width_ratios": [1, 4], "height_ratios": [2.4, 1.4]},
                         layout="constrained")
(blank, bar_ax), (size_ax, dot_ax) = axes
blank.axis("off")

# top: customers in each exact combination
bars = bar_ax.bar(x, combos.to_numpy(), color="#264653")
bar_ax.bar_label(bars, fontsize=8, padding=2)
bar_ax.set_ylabel("Customers")
bar_ax.tick_params(labelleft=True)
bar_ax.spines[["top", "right"]].set_visible(False)

# bottom right: which sets make up each combination
for i, combo in enumerate(combos.index):
    on = np.flatnonzero(combo)
    dot_ax.scatter(np.full(len(y), i), y, s=70, color="#dee2e6")
    dot_ax.plot([i, i], [on.min(), on.max()], color="#264653", linewidth=2)
    dot_ax.scatter(np.full(len(on), i), on, s=70, color="#264653", zorder=3)
dot_ax.set_xticks([])
dot_ax.tick_params(left=False)
dot_ax.spines[:].set_visible(False)

# bottom left: total size of each set
size_ax.barh(y, used.sum(), color="#8ab17d")
size_ax.set_xlabel("Set size")
size_ax.set_yticks(y, names)
size_ax.invert_xaxis()
size_ax.invert_yaxis()
size_ax.yaxis.tick_right()
size_ax.spines[["top", "left"]].set_visible(False)

bar_ax.set_title("Most common channel combinations", fontsize=14)
plt.show()
```

![UpSet plot of five channels. Website only is the largest combination with 200 customers, then App only with 121, and Website with App with 105](https://www.pythoncharts.com/python/venn-diagram-python/images/upset-plot-matplotlib.png)

Website only is the most common pattern (200 customers), followed by app only (121) and website plus app (105). The 15 bars cover 965 of the 1,110 customers who used any channel.

`DataFrame.value_counts()` does the main work: it counts each unique row of True and False values and sorts them from largest to smallest.

## Venn Diagram or UpSet Plot?

| Use | When |
|---|---|
| Venn diagram | 2 or 3 sets, and the idea of overlap matters more than precise comparison |
| UpSet plot | 4 or more sets, or readers need to rank the combinations |
| [Stacked or grouped bars](https://www.pythoncharts.com/python/stacked-bar-charts/) | The groups don't overlap |

## Similar Topics

- [Stacked bar charts in Python](https://www.pythoncharts.com/python/stacked-bar-charts/)
- [Layouts and subplots in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-subplots/)
- [Waffle charts in Python with PyWaffle](https://www.pythoncharts.com/python/waffle-chart-pywaffle/)
