在Matplotlib中绘制两个图之间的线

F.X*_*.X. 23 python matplotlib

我正在使用Matplotlib绘制两个子图,主要是:

subplot(211); imshow(a); scatter(..., ...)
subplot(212); imshow(b); scatter(..., ...)
Run Code Online (Sandbox Code Playgroud)

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

Pab*_*blo 26

你可以用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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 可能更好的做`fig.lines.append(line)`以不吹掉任何已经存在的东西. (6认同)
  • 非常好的解决方案。但是我用 jupyter 在错误的坐标处绘制了线。解决方案是在调用“transFigure = Fig.transFigure.inverted()”之前添加“fig.canvas.draw()”,以便使用正确的坐标。 (3认同)

Imp*_*est 23

在许多情况下,来自其他答案的解决方案是次优的(因为它们仅在计算点之后未对图进行任何更改时才起作用).

更好的解决方案是使用特别设计的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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 值得评论为什么`ax2.add_artist`在`ax2`而不是`ax1` github.com/matplotlib/matplotlib/issues/8744以及为什么`axesA`被设置为`ax2` (3认同)