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

Matplotlib启用LaTeX设置多色标签文字颜色不显示无报错问题

多色标签渲染问题解决方案

根因说明

matplotlib 3.4.3版本对LaTeX预加载配置的解析逻辑存在适配限制,默认加载的xcolor包未开启颜色输出适配,导致颜色命令无法被正常渲染。

方案1:基于TeX渲染的修复

调整LaTeX预加载配置,明确开启xcolor包的颜色适配选项,同时统一使用\textcolor命令设置文本颜色即可,修改后的可运行代码如下:

import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True
# 开启xcolor包的颜色名称与导出选项,适配matplotlib渲染链路
plt.rcParams['text.latex.preamble'] = r'\usepackage[usenames,dvipsnames]{xcolor}'

_, ax = plt.subplots()

plt.plot([0, 1], [0, 1], 'r')
plt.plot([0, 1], [0, 2], 'b')

plt.ylabel(r"\textcolor{blue}{y} \textcolor{red}{label}")

plt.savefig('test.pdf')
plt.show()

方案2:无需TeX依赖的原生实现

如果需要批量处理多个标签、不想依赖LaTeX环境,可关闭usetex开关,使用matplotlib原生富文本语法实现多色标签,兼容性更强、渲染速度更快:

import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = False
_, ax = plt.subplots()

plt.plot([0, 1], [0, 1], 'r')
plt.plot([0, 1], [0, 2], 'b')

# 使用原生富文本颜色标记语法
ax.set_ylabel(r'$\mathdefault{\color{blue}y \color{red}label}$')

plt.savefig('test.pdf')
plt.show()

内容的提问来源于stack exchange,提问作者I_Al-thamary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:36:02