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

2022-01-15 00:00:00 python matplotlib latex format subscript

问题描述

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

将 numpy 导入为 np将 matplotlib.pyplot 导入为 plta, b = 1, 0字符串 = "({0},{1})".format(n,l)x = np.linspace(0, 2*np.pi, 1e3)无花果 = plt.figure(0)斧头 = plt.subplot(111)ax.plot(x, np.sin(x), 'b', label = r"$E_{}$".format(string) 的函数)斧头传奇()plt.savefig("example_fig.png")

但是,此代码会生成一个图,其中只有字符串链的第一个元素string"用来:问题示例

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

解决方案

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

>>>字符串 = '(1,2)'>>>'E_{{{}}}'.format(字符串)'E_{(1,2)}'

格式化字符串语法供参考.p>

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.

解决方案

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.

相关文章