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

Matplotlib中标题已设为粗体,图例标签未加粗如何解决?

解决Seaborn直方图图例标签设为粗体的问题

要将图例标签设置为粗体,不能直接在sns.histplot()中传递fontweight参数(该函数不支持此参数),可以通过以下两种简单方法实现:

方法1:调用legend()时指定字体属性

直接在ax.legend()中使用prop参数定义字体权重:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

observed = np.array([28, 15, 21, 23, 17, 22, 19, 19, 24, 27, 20, 21, 25, 25, 16, 20, 23])

fig, ax = plt.subplots(figsize=(4, 2))

sns.histplot(ax=ax, x=observed, label="observed data") 
ax.set_title("Observed data", fontweight='bold')

# 设置图例标签为粗体
ax.legend(prop={'weight': 'bold'})

plt.show()

方法2:获取图例对象后修改文本属性

如果需要更灵活的调整,可以先获取图例对象,再逐个修改标签的字体权重:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

observed = np.array([28, 15, 21, 23, 17, 22, 19, 19, 24, 27, 20, 21, 25, 25, 16, 20, 23])

fig, ax = plt.subplots(figsize=(4, 2))

sns.histplot(ax=ax, x=observed, label="observed data") 
ax.set_title("Observed data", fontweight='bold')

# 获取图例对象并修改标签字体
legend = ax.legend()
for text in legend.get_texts():
    text.set_fontweight('bold')

plt.show()

两种方法都能实现图例标签的粗体效果,方法1更简洁,方法2适合需要对多个图例标签做不同设置的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:33:11