如何为Matplotlib坐标轴及内嵌inset轴的spine设置边角圆角效果
解决方法
可以通过隐藏坐标轴原生spine、添加自定义圆角矩形补丁的方式实现需求,无需安装第三方依赖,普通坐标轴和内嵌坐标轴都适用,可直接复用以下代码:
import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch fig, e = plt.subplots(figsize=(10, 5)) a = e.inset_axes([.1, .1, .1, .2]) b = e.inset_axes([.3, .1, .1, .2]) def set_rounded_spine(ax, radius=0.1, linewidth=1, edgecolor="black", facecolor="white"): # 隐藏默认直角spine for spine in ax.spines.values(): spine.set_visible(False) # 添加圆角边框补丁 rounded_box = FancyBboxPatch( (0, 0), 1, 1, boxstyle=f"round,pad=0,rounding_size={radius}", transform=ax.transAxes, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, zorder=-1 ) ax.add_patch(rounded_box) for ax in [a, b]: ax.set_yticks([]) ax.set_xticks([]) # 调用方法设置圆角,可调整radius控制圆角大小 set_rounded_spine(ax, radius=0.1) plt.show()
参数说明
radius:控制圆角幅度,数值越大圆角越明显,可根据视觉效果自行调整- 如果不需要坐标轴背景填充,将
facecolor参数设置为"none"即可 - 补丁的
zorder设为-1是为了避免遮挡坐标轴内的绘图内容,如果你有特殊图层需求可自行调整该值
内容的提问来源于stack exchange,提问作者user12035742
相关产品推荐
相关产品推荐

