floflo29 floflo29 - 8 months ago 69
Python Question

Plot a line between two subplots while handling the zoom with Matplotlib

I would like to be able to draw a line between two subplots in Matplotlib. Currently, I use the method provided in this SO topic: Drawing lines between two plots in Matplotlib thus using transFigure and matplotlib.lines.Line2D

However, when I zoom on my figure (both subplots share the same x and y axes), the line does not update i.e. it keeps the same coordinate in the figure frame but not in my axes frames.

Does it exist a simple way to cope with this?

Answer Source

As the comment in the linked question (Drawing lines between two plots in Matplotlib) suggests, you should use a ConnectionPatch to connect the plots. The good thing about this ConnectionPatch is not only that it is easy to realize, but also it will move and zoom together with the data.

Here is an example of how to use it.

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

fig, (ax1, ax2) = plt.subplots(1,2, sharex=True, sharey=True) 

x,y = np.arange(23), np.random.randint(0,10, size=23)
i = 10
ax1.plot(x,y, marker="s", linestyle="-.", c="r")
ax2.plot(x,y, marker="o", linestyle="", c="b")

con = ConnectionPatch(xyA=(x[i],y[i]), xyB=(x[i],y[i]), 
                      coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1, arrowstyle="-")