Matplotlib 3.10.1无法使用\underline命令,是否不支持该语法?
问题解答
你的matplotlib 3.10.1版本确实不支持在内置mathtext中使用\underline命令——官方仓库中用于支持该命令的“Support \underline in Mathtext”PR仍处于草稿状态,未合并到正式发行版本里。
现象解析
- 简单公式
$\frac{a}{b}$能正常运行,是因为这类基础Latex命令属于matplotlib内置mathtext的支持范围,无需调用系统外部Latex; - 参考旧方案时出现
RuntimeError: Failed to process string with tex because dvipng could not be found,是因为那些方案需要启用matplotlib的外部Latex渲染模式,而你的环境缺少配套的dvipng工具; - 直接执行
plt.text(.5, .5, r'Some $\underline{underlined}$ text')报错,是因为内置mathtext解析器无法识别\underline这个未被支持的命令。
可行解决方案
方案1:启用外部Latex渲染(支持\underline命令)
先安装dvipng工具(Debian/Ubuntu环境执行以下命令):
sudo apt install dvipng
然后在代码中配置matplotlib使用外部Latex:
import matplotlib.pyplot as plt # 配置使用外部Latex渲染 plt.rcParams.update({ "text.usetex": True, "font.family": "serif", }) plt.text(.5, .5, r'Some $\underline{underlined}$ text') plt.show()
方案2:无需外部Latex的替代实现
如果不想依赖外部Latex,可以直接给普通文本添加下划线:
import matplotlib.pyplot as plt # 给整段文本加下划线 plt.text(.5, .5, 'Some underlined text', underline=True, fontsize=12) plt.show() # 混合文本(部分下划线)的处理方式 fig, ax = plt.subplots() ax.text(0.2, 0.5, 'Some ', fontsize=12) ax.text(0.4, 0.5, 'underlined', fontsize=12, underline=True) ax.text(0.65, 0.5, ' text', fontsize=12) plt.show()
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

