Draw a line to connect points between subfigures

Question:

With matplotlib’s new subfigure – not subplot – but subfigure feature. I would like to draw a line between two subfigures. From my experimentation, I don’t believe connection patch (which works for subplots) works with this. Does anyone know if it possible?

Asked By: Luke Bhan

||

Answers:

ConnectionPatch works fine with subfigures, but as @JodyKlymak points out, the patch should be removed from layout calculations via set_in_layout(False).

Here is an example connecting (4, 8) on the first subfigure’s ax1a with (2, 5) on the second subfigure’s ax2:

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch

fig = plt.figure(layout='constrained')
sf1, sf2 = fig.subfigures(1, 2, wspace=0.07)

ax1a, ax1b = sf1.subplots(2, 1)
ax1a.scatter(4, 8)
ax1b.scatter(10, 15)

ax2 = sf2.subplots()
ax2.scatter(2, 5)

conn = ConnectionPatch(
    xyA=(4, 8), coordsA='data', axesA=ax1a,
    xyB=(2, 5), coordsB='data', axesB=ax2,
    color='red',
)
ax2.add_artist(conn)
conn.set_in_layout(False) # remove from layout calculations

plt.show()

figure result

Answered By: tdy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.