Matplotlib 无法渲染 LaTeX table

Matplotlib fails to render LaTeX table

我正在尝试将此 table 添加到绘图中:

示例脚本:

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['text.usetex'] = True

fig, ax = plt.subplots()

x = np.linspace(-10, 10)
ax.plot(x, x**2)

# adding table
table = r"""\begin{tabular}{cc}
\bf{Material} & \bf{Roughness ($\epsilon$)} \
\midrule
Drawn Tubing & 0.000005 \
Commercial Steel or Wrought Iron & 0.00015 \
Asphalted Cast Iron & 0.0004 \
Galvanized Iron & 0.0005 \
Wood Stave & 0.0006-0.003 \
Cast Iron & 0.00085 \
Concrete & 0.001-0.01 \
Riveted Steel & 0.003-0.03
\end{tabular}"""

ax.annotate(table, xy=(0, 60), ha='center', va='center')

plt.show()

上面的LaTeX语法是正确的,因为我在上图中得到了成功的输出。上面的脚本失败,LaTeX 无法注册存储在 table 中的字符串。如果我用 r'\bf{Testing}' 替换字符串,脚本将 运行 并输出以下内容:

我迷路了,因为上面的例子表明 matplotlib 能够处理 LaTeX,但不能处理表格环境。我不太熟悉 LaTeX,但我想知道 matplotlib 是否不会自动向序言添加一些依赖项。这个例子类似于this SO post,但是还是不行。

代码正在创建多行字符串(在每行末尾添加 \n)。如果你运行print(repr(table)),输出是:

'\begin{tabular}{cc}\n\bf{Material} & \bf{Roughness ($\epsilon$)} \\\n\midrule\nDrawn Tubing & 0.000005 \\\nCommercial Steel or Wrought Iron & 0.00015 \\\nAsphalted Cast Iron & 0.0004 \\\nGalvanized Iron & 0.0005 \\\nWood Stave & 0.0006-0.003 \\\nCast Iron & 0.00085 \\\nConcrete & 0.001-0.01 \\\nRiveted Steel & 0.003-0.03\n\end{tabular}'

您可以使用 ():

构造一个长的原始行
table = (r"\begin{tabular}{cc}"
r"\bf{Material} & \bf{Roughness ($\epsilon$)} \"
r"\hline "
r"Drawn Tubing & 0.000005 \"
r"Commercial Steel or Wrought Iron & 0.00015 \"
r"Asphalted Cast Iron & 0.0004 \"
r"Galvanized Iron & 0.0005 \"
r"Wood Stave & 0.0006-0.003 \"
r"Cast Iron & 0.00085 \"
r"Concrete & 0.001-0.01 \"
r"Riveted Steel & 0.003-0.03"
r"\end{tabular}")

将前导“r”放在每一行,以便所有部分都被解释为原始的(参见 )。

此外,我不得不用 r"\hline " 替换 midrule,因为它无法识别(需要包?)。