【问题标题】:Plot a line between two subplots while handling the zoom with Matplotlib在使用 Matplotlib 处理缩放时在两个子图之间绘制一条线
【发布时间】:2016-11-22 16:31:34
【问题描述】:

我希望能够在 Matplotlib 中的两个子图之间画一条线。目前,我使用此 SO 主题中提供的方法:Drawing lines between two plots in Matplotlib 因此使用 transFigure 和 matplotlib.lines.Line2D

但是,当我放大我的图时(两个子图共享相同的 x 和 y 轴),该线不会更新,即它在图框中保持相同的坐标,但在我的轴框中没有。

是否存在一种简单的方法来解决这个问题?

【问题讨论】:

  • 缩放是指使用 matplotlib 窗口中提供的工具交互缩放,还是以编程方式缩放?
  • 使用matplotlib绘图工具栏中提供的工具。

标签: python matplotlib


【解决方案1】:

正如链接问题 (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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多