【问题标题】:Drawing lines between two plots in Matplotlib在 Matplotlib 中的两个图之间画线
【发布时间】:2013-07-06 18:32:19
【问题描述】:

我正在使用 Matplotlib 绘制两个子图,基本上如下:

subplot(211); imshow(a); scatter(..., ...)
subplot(212); imshow(b); scatter(..., ...)

我可以在这两个子图之间画线吗?我该怎么做?

【问题讨论】:

  • 怀疑你可以用annotate做到这一点。

标签: python matplotlib


【解决方案1】:

其他答案的解决方案在许多情况下都不是最佳的(因为它们只有在计算点后没有对绘图进行任何更改时才有效)。

更好的解决方案是使用专门设计的ConnectionPatch

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

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

x,y = np.random.rand(100),np.random.rand(100)

ax1.plot(x,y,'ko')
ax2.plot(x,y,'ko')

i = 10
xy = (x[i],y[i])
con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1, color="red")
ax2.add_artist(con)

ax1.plot(x[i],y[i],'ro',markersize=10)
ax2.plot(x[i],y[i],'ro',markersize=10)


plt.show()

【讨论】:

  • 好点。这实际上比以前接受的答案更好,所以我会接受它。谢谢!
  • 值得评论一下为什么ax2.add_artistax2 而不是ax1 github.com/matplotlib/matplotlib/issues/8744 以及为什么axesA 设置为@987654330 @
  • 显然,当使用多个subplots时,我需要使用fig.add_artist,否则它似乎与constrained_layout混淆。
【解决方案2】:

您可以使用fig.line。它将任何线条添加到您的图形中。图形线的层次高于轴线,因此不需要任何轴来绘制它。

此示例在两个轴上标记相同的点。必须小心使用坐标系,但变换会为您完成所有艰苦的工作。

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

x,y = np.random.rand(100),np.random.rand(100)

ax1.plot(x,y,'ko')
ax2.plot(x,y,'ko')

i = 10

transFigure = fig.transFigure.inverted()

coord1 = transFigure.transform(ax1.transData.transform([x[i],y[i]]))
coord2 = transFigure.transform(ax2.transData.transform([x[i],y[i]]))


line = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]),
                               transform=fig.transFigure)
fig.lines = line,

ax1.plot(x[i],y[i],'ro',markersize=20)
ax2.plot(x[i],y[i],'ro',markersize=20)


plt.show()

【讨论】:

  • 最好是fig.lines.append(line),以免破坏已经存在的任何东西。
  • 非常感谢这个例子,我很难理解之前的哪个 Matplotlib 转换!不过@tcaswell 是对的,我只是在annotate 上查找了docs,而ConnectorPatch 似乎正是我想要的,所以我会尝试一下,稍后再回来!
  • 非常好的解决方案。但是我用jupyter在错误的坐标处绘制了线。解决方案是在调用transFigure = fig.transFigure.inverted() 之前添加fig.canvas.draw(),以便使用正确的坐标。
【解决方案3】:

我不确定这是否正是您正在寻找的,但这是一个跨子图绘制的简单技巧。

import matplotlib.pyplot as plt
import numpy as np

ax1=plt.figure(1).add_subplot(211)
ax2=plt.figure(1).add_subplot(212)

x_data=np.linspace(0,10,20)
ax1.plot(x_data, x_data**2,'o')
ax2.plot(x_data, x_data**3, 'o')

ax3 = plt.figure(1).add_subplot(111)
ax3.plot([5,5],[0,1],'--')
ax3.set_xlim([0,10])
ax3.axis("off")
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多