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

如何在Matplotlib中保持图例加粗文本与普通文本字号一致?

解决Matplotlib图例中加粗文本字号不一致的问题

你遇到的问题是:在Matplotlib图例中使用LaTeX的$\bf{}$命令加粗文本时,加粗部分的字号会比普通文本更大。这是因为LaTeX渲染加粗文本时,默认使用的字体与普通文本字体的字号匹配存在差异。以下是两种无需修改其他原有设置的解决方案:

方法一:使用HTML标签实现加粗(推荐)

Matplotlib支持在文本中使用HTML格式的<b>加粗标签,这种方式不会改变文本字号,且无需额外配置。直接修改你的marker4定义即可:

marker4 = ('some text that needs to go here too'+'\n'+'and is very important and just way' + '<b> too long </b>' + 'so that it wont ever look good')

修改后,图例中的加粗部分会和其他文本保持相同字号,效果符合预期。

方法二:调整LaTeX渲染配置(若必须使用LaTeX)

如果你需要保留LaTeX渲染文本,可以通过配置Matplotlib的LaTeX预导言,确保加粗字体与普通字体字号一致。在代码开头添加如下配置:

plt.rcParams.update({
    'text.usetex': True,
    'text.latex.preamble': r'\usepackage{amsmath} \usepackage[sfdefault]{cabin}',
    'font.family': 'sans-serif'
})

同时将$\bf{}$替换为LaTeX标准的\textbf{}命令:

marker4 = ('some text that needs to go here too'+'\n'+'and is very important and just way' + r'\textbf{ too long }' + 'so that it wont ever look good')

这种方法通过指定统一的无衬线字体族,消除了加粗与普通文本的字号差异。

修改后的完整代码

以下是应用方法一修改后的完整代码:

import matplotlib.pyplot as plt
from matplotlib import ticker
fmt = '$%g$'
fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
xticks = ticker.FormatStrFormatter(fmt)
yticks = ticker.FormatStrFormatter(fmt)
x1 = plt.scatter([1,2],[2,3], color='b')
x2 = plt.scatter([2,3],[4,3], color='r')
x3 = plt.scatter([1,3],[4,5], color='k')
x4 = plt.scatter(0, 0, color='white')
marker1 = 'marker 1'
marker2 = 'marker 2'
marker3 = 'marker 3'
plt.xlabel("x axis")
plt.ylabel("y axis")
# 使用HTML <b>标签实现加粗,保持字号一致
marker4 = ('some text that needs to go here too'+'\n'+'and is very important and just way' + '<b> too long </b>' + 'so that it wont ever look good')
legend_two = plt.legend([x1, x4],[marker1, marker4],
                        fontsize=8,
                        title='some other title',
                        title_fontsize=10,
                        bbox_to_anchor=(0.5, 0.0),
                        bbox_transform=fig.transFigure,
                        ncol=1,
                        loc="upper left",
                        borderaxespad=0)
plt.legend([x1,x2,x3], [marker1,marker2,marker3],
           fontsize=8,
           title=r'$\bf{some title}$',
           title_fontsize=10,
           bbox_to_anchor=(0.0, 0.0),
           bbox_transform=fig.transFigure,
           ncol=3,
           loc="upper left",
           borderaxespad=0)
plt.gca().add_artist(legend_two)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:45:34