Python - 分割带有LaTeX格式的字符串

1 投票
1 回答
1120 浏览
提问于 2025-04-18 06:03

我有一个公式需要在图表上显示。这个公式比较长,所以我想把它分开,确保每行不超过80个字符。

下面是一个最小可重现的例子:

import matplotlib.pyplot as plt

num = 25

text = (r"$RE_{%d}$ = $\frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) - |B_t - f_h+f_g)|}{B}$") % num

fig = plt.figure()
ax = fig.add_subplot(111)

plt.scatter([0., 1.], [0., 1.])
plt.text(0.5, 0.5, text, transform=ax.transAxes)

plt.show()

如果我这样写,图表可以正常生成,但当我尝试换行的时候,就会出现各种错误。

我该怎么做呢?

1 个回答

2

一种简单的方法就是直接使用连接字符串:

text = (r"$RE_{%d}$ = $\frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) " +
        r" - |B_t - f_h+f_g)|}{B}$") % num

你也可以使用三重引号的多行字符串,不过这样的话你需要手动处理换行:

def lf2space(s):
  return " ".join(s.split("\n"))

text = lf2space(r"""
    $RE_{%d} = 
       \frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) 
                - |B_t - f_h+f_g)|}
            {B}$
  """ % num)

撰写回答