【问题标题】:Drawing filled shapes between different axes in matplotlib在 matplotlib 中的不同轴之间绘制填充形状
【发布时间】:2018-07-10 23:45:03
【问题描述】:

我想用实心三角形表示主子图中的一些数据点与其他一些子图之间的关系。 我发现 Connection Patch 允许您在不同轴之间绘制线条/箭头,但没有填充形状。由于我想要一个实心三角形,我试图提取补丁的坐标(在主子图的轴坐标中)并绘制一个具有相同坐标的多边形。然而,多边形随后被子图的轴切断。我怎样才能使它在情节之间也可见?

This is how it currently looks like.

这是一个最小的工作示例:

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

fig, ax = plt.subplots()
ax.axis('off')

grid_t = gs.GridSpec(4,3)
ax0a = fig.add_subplot(grid_t[0:1,0:1])
ax0b = fig.add_subplot(grid_t[0:1,1:2])
ax0c = fig.add_subplot(grid_t[0:1,2:3])
ax1 = fig.add_subplot(grid_t[1:4,:])

xl = ax0a.get_xlim()
yl = ax0a.get_ylim()
ptAl = (xl[0], yl[0])
ptAr = (xl[1], yl[0])

ptD1 = (0,0)
ptD2 = (1,1)
ptD3 = (2,1)

ax1.plot([-1,0,1,2,3],[2,0,1,1,-1],'ko')

from matplotlib.patches import ConnectionPatch

for pts,axs,num in [[ptD1,ax0a,1],[ptD2,ax0b,2],[ptD3,ax0c,3]]:

    con1 = ConnectionPatch(xyA=pts, xyB=ptAl, coordsA="data", coordsB="data",
                          axesA=ax1, axesB=axs,color='grey',shrinkA=0,shrinkB=0)
    ax1.add_artist(con1)
    con2 = ConnectionPatch(xyA=pts, xyB=ptAr, coordsA="data", coordsB="data",
                          axesA=ax1, axesB=axs,color='grey',shrinkA=0,shrinkB=0)
    ax1.add_artist(con2)

    line2=con2.get_path().vertices
    line1=con1.get_path().vertices

    zoomcoords = sorted(np.concatenate((line1[1:],line2)),key=lambda x: x[0])
    triangle = plt.Polygon(zoomcoords,ec='black',fc='red',zorder=100)
    ax1.add_artist(triangle)

【问题讨论】:

    标签: python matplotlib zooming multiple-axes


    【解决方案1】:

    你可以设置clip_on=False:

    triangle = plt.Polygon(zoomcoords,ec='black',fc='red',zorder=100, clip_on=False)
    

    【讨论】:

    • 谢谢,这很有帮助!我现在怎么能让小地块的 x 轴在前景中?如果我设置zorder=0,三角形落在主子图的轴后面,但仍覆盖小子图的 x 轴。
    • 我认为您想将小轴的 zorder 设置为高于大轴的 zorder。
    • 将 ax0a 通过 ax0c 分配给 'zorder = 1' 而三角形位于 'zorder =0' 对我来说是诀窍。再次感谢!