python - 使用 Matplotlib 处理缩放时在两个子图之间绘制一条线

标签 python matplotlib

我希望能够在 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/

相关文章:

shell 命令上的 Python 复杂字符串插值

python - 如何在标签中绘制带有汉字的图形

python - 使用 matplotlib 在 python 中绘制曲线决策边界

python - 我该如何修复这个算法?

python - Plotly:如何从数据框中绘制桑基图?

python - 在 python 中绘制自定义函数

python - matplotlib.pyplot 没有属性 'style'

python:如何在 plt.show() 之后保持脚本运行

python - 建立新连接失败: [Errno -2] Name or service not known

python - 具有复杂文件树的模块中的覆盖函数