在Matplotlib中

时间:2017-01-10 17:31:18

标签: python matplotlib

我正在尝试生成一个图形,其中我从子图的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()

enter image description here 关于行开始和结束的地方(它们可能是相关的)我有2个问题:

  1. 该行中的行不会完全位于底部子图中的位置。它们应该都以红色三角形的中心结束,但它们会向左偏移一点。
  2. 这些线条并不完全在它们开始的子图的角落处终止。如果仔细观察地块d的底角,就可以看到这一点。和f。

1 个答案:

答案 0 :(得分:0)

新推出的ConnectionPatch将更优雅地解决您的问题。

以下代码应与您的原始帖子等效(请注意,未经测试)

OVERRIDING