如何在 Python matplotlib 中的 LaTeXed 下标中包含字符串链

How to include a string chain in a LaTeXed subscript in Python matplotlib

我想用 LaTeX 在 matplotlib 图的图例中写一个带有下标的变量。此类问题的一种可能代码是:

import numpy as np
import matplotlib.pyplot as plt

a, b = 1, 0
string = "({0},{1})".format(n,l)
x = np.linspace(0, 2*np.pi, 1e3)

fig = plt.figure(0)
ax = plt.subplot(111)
ax.plot(x, np.sin(x), 'b', label = r"Function for $E_{}$".format(string))
ax.legend()
plt.savefig("example_fig.png")

但是,此代码生成的图仅使用了字符串链“string”的第一个元素: Example of the problem

我尝试使用 .format{string[:]}$E_{{}}$ 来解决这个问题,但它似乎不起作用,我也没有更多的想法。

你需要使用三个大括号,一个大括号被另一个大括号转义,所以两个 {{ 打印一个文字 {。第三个被格式化。

>>> string = '(1,2)'
>>> 'E_{{{}}}'.format(string)
'E_{(1,2)}'

Format String Syntax供参考。