0

I want to mark a line over two aligned subplots. Therefore, I use matplotlib.patches.ConnectionPatch as suggested in other answers. It worked already in other examples, but here for the second time, the line just is cut off at the second plot area.

How do I assure that the ConnectionPatch is plotted in the front?

I tried playing around with zorder, but did not find a solution yet.

enter image description here

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

xes=[-2, 0, 2]
field=[0, -10, 0]
potential=[-20, 0, 20]

fig, axs = plt.subplots(2, 1, sharex=True)

axs[0].plot(xes, field)
axs[1].plot(xes, potential)

# line over both plots
_, ytop = axs[0].get_ylim()
ybot, _ = axs[1].get_ylim()
n_p_border = ConnectionPatch(xyA=(0., ytop), xyB=(0., ybot), 
                             coordsA='data', coordsB='data',
                             axesA=axs[0], axesB=axs[1], lw=3)
print(n_p_border)
axs[0].add_artist(n_p_border)
Simon
  • 495
  • 1
  • 4
  • 18

1 Answers1

1

You would need to inverse the role of the two axes. This is also shown in Drawing lines between two plots in Matplotlib.

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

xes=[-2, 0, 2]
field=[0, -10, 0]
potential=[-20, 0, 20]

fig, axs = plt.subplots(2, 1, sharex=True)

axs[0].plot(xes, field)
axs[1].plot(xes, potential)

# line over both plots
_, ytop = axs[0].get_ylim()
ybot, _ = axs[1].get_ylim()
n_p_border = ConnectionPatch(xyA=(0., ybot), xyB=(0., ytop), 
                             coordsA='data', coordsB='data',
                             axesA=axs[1], axesB=axs[0], lw=3)

axs[1].add_artist(n_p_border)
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Oh so simple. The idea just is to draw the `ConnectionPath` on the last drawn axis. Thanks. – Simon Dec 02 '18 at 13:32