在matplotlib中绘制不同轴之间的填充形状

2024-10-02 00:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个填充的三角形表示主子图中的一些数据点和其他一些子图中的数据点之间的关系。 我发现连接补丁允许你在不同的轴之间画线/箭头,但是没有填充的形状。因为我想要一个填充的三角形,所以我试图提取面片的坐标(在主子块的轴坐标中),并用相同的坐标绘制一个多边形。然而,多边形会被子图的轴截断。我怎样才能使它在两个图之间也可见呢?在

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)

Tags: importadddatagetmatplotlibasfigplt

热门问题