matplotlib中的TeX渲染、大括号和字符串格式化语法

24 投票
3 回答
9878 浏览
提问于 2025-04-16 18:01

我在我的 matplotlib 图表中使用以下代码来渲染 TeX 注释:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
rc('font', family='serif')

voltage = 220

notes = r"\noindent $V_2 = {0:.5} V$".format(voltage)

plt.annotate(notes, xy=(5,5), xytext=(7,7))
plt.show()

这个方法运行得很好,但我有一个小问题,就是 V 是一个单位,所以它应该用正常的文本模式,而不是(斜体的)数学模式。我尝试了以下字符串:

notes = r"\noindent $V_2 = {0:.5} \text{V}$".format(voltage)

但是这会报错,因为 {大括号} 是 Python 字符串格式化语法的一部分。在上面的代码中,只有 {0:.5} 是正确的;{V} 被当作不认识的东西。例如:

s1 = "Hello"
s2 = "World!"
print "Some string {0} {1}".format(s1, s2)

应该输出 Some string Hello World!

我该如何确保 TeX 的 {大括号} 不会和 Python 的 {大括号} 发生冲突呢?

3 个回答

2

我更喜欢用'%'来格式化,而不是用python的'{}',这样可以避免很多大括号。

所以为了显示像 3*pi/2 这样的内容,我会用下面的代码:

r'\frac{%.0f\pi}{2}' % (3)

而不是用:

r'\frac{{{:.0f}\pi}}{{2}}'.format(3)

在Jupyter中使用时,代码会是这样的:

from IPython.display import display, Math, Latex
display(Math(  r'\frac{%.0f\pi}{2}' % (3)  ))
6

你需要用双大括号把它们包起来:

>>> print '{{asd}} {0}'.format('foo')
{asd} foo
29

你需要把大括号写两次,这样它们才会被当作普通字符处理:

r"\noindent $V_2 = {0:.5} \text{{V}}$".format(voltage)

顺便说一下,你也可以这样写:

\text V

但最好的写法是:

\mathrm V

因为单位其实并不是一个文本符号。

撰写回答