You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Matplotlib图例标题设置半透明红色背景

解决Matplotlib图例标题背景设置问题

要给图例标题设置透明度为0.5的红色背景,你可以通过获取标题的bbox_patch属性来修改其背景样式,具体代码如下:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1,2,3], [1,2,3], label='Series')
legend = ax.legend(title='Title')

# 获取图例标题的背景补丁,设置颜色和透明度
title = legend.get_title()
title_bbox = title.get_bbox_patch()
title_bbox.set_facecolor('red')
title_bbox.set_alpha(0.5)

plt.show()

关键说明:

  • 使用legend.get_title()直接获取图例标题对象,比访问内部私有属性(如_legend_title_box)更稳定,能避免Matplotlib版本更新带来的兼容性问题
  • 通过get_bbox_patch()获取标题的背景渲染补丁,再用set_facecolor()设置背景色,set_alpha()调整透明度

内容的提问来源于stack exchange,提问作者jII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:03:13