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

Draw two and three set Venn diagrams with matplotlib-venn, and build an UpSet plot in Matplotlib for four or more sets.

To make a Venn diagram in Python, install 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.

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

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.

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

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.

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

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:

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

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 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:

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

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 The groups don't overlap

Similar Topics