我正在尝试生成一个图形,其中我从子图的2个角到不同子图中的点运行。我在阅读Drawing lines between two plots in Matplotlib时取得了一些成功,但结果情节并不完全正确。我创建了一个简化的例子来试图说明我的问题。
import numpy as np
from matplotlib import gridspec,lines
import matplotlib.pyplot as plt
def corner_to_point(point_ax,corner_ax,point,corners,fig):
transFigure = fig.transFigure.inverted()
coord1 = transFigure.transform(point_ax.transData.transform(point))
for elem in corners:
x0,x1 = corner_ax.get_xlim()
y0,y1 = corner_ax.get_ylim()
if elem == 1: # upper left
c = [x0,y1]
elif elem == 2: # upper right
c = [x1,y1]
elif elem == 3: # lower right
c = [x1,y0]
else: # lower left
c = [x0,y0]
coord2 = transFigure.transform(corner_ax.transData.transform(c))
line = lines.Line2D((coord1[0],coord2[0]),
(coord1[1],coord2[1]),
transform=fig.transFigure,color='k')
fig.lines.append(line)
fig = plt.figure(figsize=(8,7.5))
# set up the figure layout
outer = gridspec.GridSpec(2,1,height_ratios = [2,1.5],
hspace = 0.2)
gs1 = gridspec.GridSpecFromSubplotSpec(2,3,
subplot_spec = outer[0],
hspace = 0.0,
wspace = 0.0)
gs2 = gridspec.GridSpecFromSubplotSpec(1,1, subplot_spec = outer[1])
xs = np.linspace(-np.pi,np.pi)
funcs = [np.sin,np.cos,np.tan,np.sinh,np.cosh,np.tanh]
labels = ['a','b','c','d','e','f']
grid = []
for i,func,label in zip(range(6),funcs,labels):
ax = plt.subplot(gs1[i])
ax.plot(xs,func(xs))
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.text(0.05, 0.95, label,
verticalalignment='top', horizontalalignment='left',
transform=ax.transAxes,fontsize=15)
grid.append(ax)
ax2 = plt.subplot(gs2[0])
ax2.plot(xs,np.sin(xs), 'b-',
[-2.25,3],[0,0],'r^')
corner_to_point(ax2,grid[3],[-2.25,0],[3,4],fig)
corner_to_point(ax2,grid[5],[3,0],[3,4],fig)
plt.show()