How to Make a Chord Diagram in Python with pyCirclize

Turn a from-to table into a chord diagram with pyCirclize, add direction arrows, set colors, highlight one group and know when a heatmap is clearer.

A chord diagram shows flows between groups arranged around a circle, with ribbons whose widths are the amounts. In Python, pass a "from × to" DataFrame to pycirclize.Circos.chord_diagram(), then draw it with plotfig(). This post uses pyCirclize 1.10.1 (pip install pycirclize) and Matplotlib 3.11.

Quick Example

People moving between five made-up districts in a year. Rows are where they left, columns where they went:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pycirclize import Circos

districts = ["Center", "Harbor", "Hills", "Park", "Station"]
moves = pd.DataFrame(
    [[0,  120, 260, 180,  90],
     [210,  0,  60,  40, 110],
     [80,  30,   0,  95,  20],
     [100, 45, 130,   0,  35],
     [240, 85,  50,  70,   0]],
    index=districts, columns=districts)

colors = {"Center": "#d1495b", "Harbor": "#00798c", "Hills": "#edae49",
          "Park": "#30638e", "Station": "#8d6a9f"}

circos = Circos.chord_diagram(
    moves,
    space=4,
    cmap=colors,
    ticks_interval=200,
    label_kws=dict(r=119, size=12),
    link_kws=dict(direction=1, alpha=0.65, lw=0.4, ec="white"),
)
fig = circos.plotfig(figsize=(7, 7))
plt.show()

Chord diagram of moves between five districts, with colored ribbons pointing from the origin district to the destination

How do I read it?

Each outer arc is a district, and its length counts everyone who left plus everyone who arrived. A ribbon takes the color of the origin, and direction=1 gives it an arrow head at the destination.

summary = pd.DataFrame({"left": moves.sum(axis=1), "arrived": moves.sum(axis=0)})
summary["net"] = summary.arrived - summary.left
print(summary)
         left  arrived  net
Center    650      630  -20
Harbor    420      280 -140
Hills     225      500  275
Park      310      385   75
Station   445      255 -190

Hills gains the most (275 people) and Station loses the most (190). Center has the largest arc, yet its net change is only -20 because arrivals and departures nearly cancel.

Highlight one group's flows

link_kws_handler receives the origin and destination of each ribbon and returns settings for it. Gray out everything except moves from Center:

def style(origin, destination):
    if origin == "Center":
        return dict(alpha=0.85, zorder=2)
    return dict(fc="#d9d9d9", alpha=0.5, zorder=1)

circos = Circos.chord_diagram(
    moves, space=4, cmap=colors, label_kws=dict(r=108, size=12),
    link_kws=dict(direction=1), link_kws_handler=style,
)
fig = circos.plotfig(figsize=(7, 7))
plt.show()

Chord diagram with moves out of the Center district in red and all other ribbons gray

Show net flows only

Two-way traffic is often mostly balanced. Subtract the reverse direction and keep the positive part to see who gained from whom.

net = (moves - moves.T).clip(lower=0)
print(net)

circos = Circos.chord_diagram(
    net, space=5, cmap=colors, order="desc",
    label_kws=dict(r=108, size=12),
    link_kws=dict(direction=1, alpha=0.8),
)
fig = circos.plotfig(figsize=(7, 7))
plt.show()
         Center  Harbor  Hills  Park  Station
Center        0       0    180    80        0
Harbor       90       0     30     0       25
Hills         0       0      0     0        0
Park          0       5     35     0        0
Station     150       0     30    35        0

Chord diagram of net movement between districts, with far fewer and thinner ribbons

order="desc" sorts the sectors by size. You can also pass a list of names.

Chord diagram or heatmap?

A heatmap of the same matrix is easier to read exactly, and it scales to more groups.

fig, ax = plt.subplots(figsize=(6.2, 5))
image = ax.imshow(moves, cmap="Blues")
for (i, j), value in np.ndenumerate(moves.to_numpy()):
    ax.text(j, i, value if value else "–", ha="center", va="center",
            color="white" if value > 150 else "black")
ax.set_xticks(range(5), districts)
ax.set_yticks(range(5), districts)
ax.set_xlabel("Moved to")
ax.set_ylabel("Moved from")
fig.colorbar(image, label="People")
plt.show()

Heatmap of the move counts between districts with each value written in its cell

Use When
Chord diagram An overview of connections among about 3 to 10 groups
Heatmap Readers need values, or there are many groups
Sankey diagram Flows move through stages in one direction
Network graph The structure of connections matters more than amounts

Practical tips

  • The diagonal is zero here. Nonzero values on it draw loops back to the same sector.
  • Color ribbons consistently, by origin or by the group your story is about.
  • Merge small groups into "Other" before the circle gets crowded.
  • Save with circos.savefig("chord.png").

Similar Topics