How to include a string chain in a LaTeXed subscript in Python matplotlib [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-02 00:45:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!