1

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?

Community
  • 1
  • 1
floflo29
  • 2,261
  • 2
  • 22
  • 45

1 Answers1

3

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)
x=np.sort(x)
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="-")

ax2.add_artist(con)

plt.show()
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712