我希望能够在 Matplotlib 中的两个子图之间画一条线。目前,我使用此SO主题中提供的方法:Drawing lines between two plots in Matplotlib因此使用 transFigure 和 matplotlib.lines.Line2D
但是,当我放大图形时(两个子图共享相同的 x 和 y 轴),该线不会更新,即它在图形框架中保持相同的坐标,但不在我的轴框架中保持相同的坐标。
有没有一种简单的方法来解决这个问题?
最佳答案
正如链接问题( Drawing lines between two plots in Matplotlib )中的评论所建议的,您应该使用 ConnectionPatch
连接情节。这个ConnectionPatch
的好处不仅在于它很容易实现,而且它会随着数据一起移动和缩放。
这是如何使用它的示例。
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()
关于python - 使用 Matplotlib 处理缩放时在两个子图之间绘制一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747018/