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

如何在Matplotlib中设置轴标题部分文字加粗、部分正常

解决Matplotlib轴标题部分文字加粗的问题

Matplotlib的set_title方法无法通过参数直接给标题内的部分文字设置不同字体粗细,你需要用Matplotlib支持的TeX格式标记来实现局部加粗,具体修改如下:

核心修改

把原本的ax.set_title代码替换成:

# 用TeX标记\textbf{}包裹需要加粗的player_value,注意f-string里要转义大括号
ax.set_title(f'{feature}\n\\textbf{{{int(player_value)}}}', color='#100097', loc='right')

注意:这里的双大括号是为了在f-string中输出单个大括号,让Matplotlib识别TeX的加粗标记;同时要去掉原来的fontweight="bold"参数,避免全局加粗覆盖局部设置。

完整修改后的代码

# Features to plot
features = ['Overall Rating', 'Shooting Rating', 'Creativity Rating', 'Passing Rating', 
            'Dribbling Rating', 'Defending Rating', 'Pressing Rating', 'Aerial Rating']

# Loop through each feature and create density plots
for i, feature in enumerate(features):
    ax = axes[i]
    # Draw the density plot using the current feature column from the DataFrame
    sns.kdeplot(df[feature], shade=True, color='white', ax=ax)
    # Plot marker for df
    player_value = df[feature].values[0]
    # 修改后的标题设置:feature正常粗细,player_value加粗
    ax.set_title(f'{feature}\n\\textbf{{{int(player_value)}}}', color='#100097', loc='right')

补充说明

如果你的Matplotlib环境不支持默认的TeX标记渲染,可以提前添加以下配置开启mathtext支持:

import matplotlib.pyplot as plt
plt.rcParams['mathtext.fontset'] = 'stix'
plt.rcParams['font.family'] = 'STIXGeneral'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:19:58