Matplotlib Pyplot按类别分组图例标签及解决分组后空格问题
在Matplotlib中分组图例条目并消除组标签前的多余空格
要实现图例按组划分且避免组名重复,同时解决组标签前的空格问题,可以通过以下两种方式优化代码:
方案一:基于原有代码修正
原代码存在两处问题:
- 判断线条样式时错误调用了
get_linestyle方法(未加括号) - 未针对组标签单独处理空格,全局设置
handlelength=0会影响正常线条的图例标记
修改后的代码:
import matplotlib.pyplot as plt # 添加组标签(空线条,不显示) group_handles = [ plt.plot([], [], linestyle="None", label="Group 1:")[0], plt.plot([], [], linestyle="None", label="Group 2:")[0] ] # 绘制各组线条 plt.plot([1,2],[4,5],linestyle="--",label="Line 1") plt.plot([1,2],[4,6],label="Line 3") plt.plot([1,2],[4,7],label="Line 2") plt.plot([1,2],[4,8],label="Line 4") # 创建图例并设置列数 leg = plt.legend(ncol=3) # 处理组标签的可见性和空格 for idx, handle in enumerate(leg.legendHandles): if handle in group_handles: handle.set_visible(False) # 单独将该条目的handle宽度设为0,消除前导空格 leg._legend_box.get_children()[0].get_children()[idx].set_width(0) plt.show()
方案二:手动构建分组图例条目
直接定义图例的handles和labels列表,逻辑更直观可控:
import matplotlib.pyplot as plt # 绘制并保存线条对象 line1, = plt.plot([1,2],[4,5],linestyle="--") line3, = plt.plot([1,2],[4,6]) line2, = plt.plot([1,2],[4,7]) line4, = plt.plot([1,2],[4,8]) # 构建分组的图例元素:空矩形作为组标签的占位handle handles = [ plt.Rectangle((0,0), 0, 0, visible=False), line1, line2, plt.Rectangle((0,0), 0, 0, visible=False), line3, line4 ] labels = [ "Group 1:", "Line 1", "Line 2", "Group 2:", "Line 3", "Line 4" ] # 创建图例,设置列数,空handle的handlelength设为0 leg = plt.legend(handles=handles, labels=labels, ncol=3, handlelength=0) # 恢复正常线条的handle长度为默认值 default_handle_length = plt.rcParams['legend.handlelength'] for idx, handle in enumerate(leg.legendHandles): if idx not in [0, 3]: leg._legend_box.get_children()[0].get_children()[idx].set_width(default_handle_length) plt.show()
效果说明
两种方案都能实现:
- 组标签仅显示一次,无重复冗余内容
- 组标签前无多余空格,正常线条的图例标记完整保留
内容的提问来源于stack exchange,提问作者CLRW97
相关产品推荐
相关产品推荐

