如何在Python matplotlib中的LaTeXed下标中包含字符串链 [英] How to include a string chain in a LaTeXed subscript in Python matplotlib
问题描述
我想在matplotlib图的图例中使用LaTeX编写一个带下标的变量.解决此类问题的可能代码如下:
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")
但是,此代码生成了一个图,其中仅使用了字符串链"string"的第一个元素: 问题示例
However, this code produces a plot where only the first element of the string chain "string" is used: Example of the problem
我尝试使用.format{string[:]}
或$E_{{}}$
解决此问题,但是它似乎不起作用,并且我没有更多的想法.
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.
推荐答案
您需要使用三个花括号,一个花括号与另一个花括号一起转义,因此两个{{
打印一个文字{
.第三个被格式化.
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)}'
格式化字符串语法供参考.
这篇关于如何在Python matplotlib中的LaTeXed下标中包含字符串链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!