ConnectionPath隐藏在子图后面

时间:2018-12-02 12:39:46

标签: python matplotlib

我想在两个对齐的子图上标记一条线。因此,我按照其他答案中的建议使用matplotlib.patches.ConnectionPatch。在其他示例中也可以使用,但是这是第二次在第二个绘图区域截断了线。

如何确保将ConnectionPatch绘制在前面?

我尝试使用zorder,但尚未找到解决方案。

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)

1 个答案:

答案 0 :(得分:1)

您需要颠倒两个轴的角色。这也显示在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