如何添加FancyBbox作为Matplotlib图例?
问题
想要在Matplotlib图例中添加一系列FancyBbox,参考官方Fancybox示例,但编写的代码里图例中的FancyBbox形状和图中显示的不一致,需要修正代码。
原代码如下:
import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch styles = ['darrow', 'round4', 'roundtooth', 'square'] coords = [(0.2, 0.2), (0.2, 0.8), (0.8, 0.2), (0.8, 0.8)] colors = ['red', 'green', 'blue', 'orange'] weights = ['bold', 'ultralight', 'normal', 'heavy'] fig, ax = plt.subplots() patches = [] for style, color, weight, (x, y) in zip(styles, colors, weights, coords): ax.text(x, y, style, fontsize=12, fontweight=weight, ha='center', va='center', bbox=dict(boxstyle=style, facecolor=color, alpha=0.5, edgecolor='black')) legend_patch = FancyBboxPatch((0, 0), width=1, height=1, boxstyle=style, facecolor=color, edgecolor='black', alpha=0.5, transform=ax.transAxes, label='Bbox') patches.append(legend_patch) ax.legend(patches, styles, loc='center', handleheight=2) plt.show()
解决方案
问题出在图例中FancyBboxPatch的坐标变换和尺寸设置上,直接绑定坐标轴变换会导致形状被错误缩放,默认尺寸也不匹配图例容器。
修正后的代码如下:
import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch styles = ['darrow', 'round4', 'roundtooth', 'square'] coords = [(0.2, 0.2), (0.2, 0.8), (0.8, 0.2), (0.8, 0.8)] colors = ['red', 'green', 'blue', 'orange'] weights = ['bold', 'ultralight', 'normal', 'heavy'] fig, ax = plt.subplots() patches = [] for style, color, weight, (x, y) in zip(styles, colors, weights, coords): # 绘制图中的文本与Bbox ax.text(x, y, style, fontsize=12, fontweight=weight, ha='center', va='center', bbox=dict(boxstyle=style, facecolor=color, alpha=0.5, edgecolor='black')) # 创建适配图例的FancyBboxPatch:移除坐标轴变换,调整尺寸让形状居中显示 legend_patch = FancyBboxPatch((-0.4, -0.3), width=0.8, height=0.6, boxstyle=style, facecolor=color, edgecolor='black', alpha=0.5) patches.append(legend_patch) # 调整图例手柄参数,确保形状完整展示 ax.legend(patches, styles, loc='center', handlelength=1.5, handleheight=1.2) plt.show()
修正说明
- 移除
transform=ax.transAxes:图例的Patch无需绑定坐标轴变换,Matplotlib图例系统会自动处理其坐标空间。 - 调整Patch原点与尺寸:将原点设为
(-0.4, -0.3)、宽高设为0.8和0.6,保证形状在图例手柄区域内居中且完整。 - 优化图例参数:通过
handlelength和handleheight给不同样式的FancyBbox预留足够显示空间,避免形状被截断。
内容的提问来源于stack exchange,提问作者VERBOSE
相关产品推荐
相关产品推荐

