如何修改Matplotlib Inset Axes的矩形连接线为仅显示两条线?
实现Matplotlib Inset Axes仅显示两条连接线的方案
不需要手动绘制线条,直接通过调整mark_inset生成的补丁属性就能实现需求:
步骤1:创建基础嵌入轴并生成标记
先正常绘制主图与嵌入子图,调用mark_inset时设置填充透明,避免遮挡底层内容:
from matplotlib.pyplot import subplots from mpl_toolkits.axes_grid1.inset_locator import mark_inset fig, ax = subplots() ax.plot(range(1,6), [x**2 for x in range(1,6)]) # 创建嵌入子图,参数为[左, 下, 宽, 高],占主图比例 ax_inset = ax.inset_axes([0.6, 0.6, 0.3, 0.3]) ax_inset.plot(range(3,6), [x**2 for x in range(3,6)]) # 生成标记,fc设为'none'取消填充,ec设置线条颜色 mark = mark_inset(ax, ax_inset, loc1=2, loc2=4, fc='none', ec='black')
步骤2:控制矩形补丁的可见边
mark_inset会生成两个矩形补丁:主图上的放大框(patchA)和子图上的框(patchB)。通过set_visible_edges方法指定需要显示的边即可:
# 主图放大框:仅保留左、上两条边 mark.patchA.set_visible_edges(['left', 'top']) # 子图框:仅保留右、下两条边 mark.patchB.set_visible_edges(['right', 'bottom'])
灵活调整
如果需要显示其他组合的线条(比如两条竖线),只需修改set_visible_edges的参数,可选边值包括'left'、'right'、'top'、'bottom'。同时配合loc1和loc2参数,可调整连接线的对应连接位置。
内容的提问来源于stack exchange,提问作者Luke Bhan
相关产品推荐
相关产品推荐

