问题
I want to write in the legend of a matplotlib figure a variable with a subscript using LaTeX. One possible code for this kind of problem could be:
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")
However, this code produces a plot where only the first element of the string chain "string" is used: Example of the problem
I tried to solve this problem using .format{string[:]}
or $E_{{}}$
but it doesn't seem to work, and I don't have more ideas.
回答1:
You need to use three braces, a brace is escaped with another brace so two {{
print a literal {
. The third gets formatted.
>>> string = '(1,2)'
>>> 'E_{{{}}}'.format(string)
'E_{(1,2)}'
Format String Syntax for reference.
来源:https://stackoverflow.com/questions/34480756/how-to-include-a-string-chain-in-a-latexed-subscript-in-python-matplotlib