python - 如何使用 mpl_toolkits.axes_grid1.inset_locator.mark_inset 控制 zorder 和裁剪?

标签 python python-3.x matplotlib

在带有插图轴的图中,我想使用 mpl_toolkits.axes_grid1.inset_locator.mark_inset 标记插图。但是,我在控制 zorder 和剪切标记插图的结果线时遇到了麻烦。插入轴设置为 zorder=4,我正在使用:

fig = plt.figure()
fig.set_tight_layout(False)
ax = fig.gca()

x = np.arange(4500.0, 10000.0)
ax.plot(x, 700-x/20.0+20*np.sin(x/8.0), label="Skylines")


from mpl_toolkits.axes_grid1.inset_locator import InsetPosition, mark_inset, inset_axes

inset_ax = fig.add_axes([0,0,1,1], zorder=4, frameon=True)
inset_ax.set_axes_locator(InsetPosition(ax, [0.1, 0.1, 0.4, 0.5]))

inset_ax.plot(x, 700-x/20.0+20*np.sin(x/8.0))

inset_ax.set_xlim(8800, 8850)
inset_ax.set_ylim(230, 285)
# inset_ax.set_ylim(100, 600)

mark_inset(ax, inset_ax, loc1=2, loc2=3, linewidth=0.7, fc="None", ec='k', alpha=0.4, clip_on=True, zorder=3)

ax.axhline(y=300, c='r', label="Test")

leg = ax.legend(ncol=1, loc='upper center', frameon=True, framealpha=1.0)
leg.set_zorder(5)

plt.show()

对于 y 极限内的两种不同情况,结果为

enter image description here

enter image description here

这里不需要的行为是,插入线分别出现在插入轴上(而标记为“测试”的线很好地放置在插入轴后面)和主轴外部(并穿过图例)。我本希望使用 zorderclip_on 参数来解决这个问题,但它们似乎没有效果。

最佳答案

案例1

zorder 在每个轴的基础上进行评估。由于连接线被添加到插入轴,因此它们将始终位于轴背景的顶部。一种选择是将它们从插入轴中删除并将它们添加到原始轴中。

案例2

连接器在 matplotlib 源代码中明确没有被剪切,因为作为插入轴的一部分,您永远不希望它们被插入轴剪切。

但是,如果它们是原始轴的一部分,您可以再次将剪切设置为打开。

总计

ret = mark_inset(ax, inset_ax, loc1=2, loc2=3, linewidth=0.7, fc="None", ec='k', alpha=0.4)

for bc in ret[1:]:
    bc.remove()
    ax.add_patch(bc)
    bc.set_zorder(4)
    bc.set_clip_on(True)

enter image description here enter image description here

关于python - 如何使用 mpl_toolkits.axes_grid1.inset_locator.mark_inset 控制 zorder 和裁剪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56932448/

相关文章:

python - 如何删除尾随换行符?

mysql - 如何从 SQL 快照访问数据

Python:在一个 IF 语句中组合 NOT、AND、IN

python - 如何在 Python 3 中使用 ascii 函数?

python - matplotlib 轴标签与数据箱不对齐

matplotlib - 我不知道如何制作一个新的 matplotlib 图

Python-Camelot 提取空表

python - 结合来自多个子项目的 Sphinx 文档 : Handling indices, 同步配置等

python - Django rest framework Router - 如何添加自定义 URL 和 View 功能

matplotlib - PyCharm 和外部库