Matplotlib - 在 LateX 表达式中使用变量
Matplotlib - using variables in LateX expressions
我想使用 LateX 格式构建一个表达式,其中出现了一些数字,但在 LateX 表达式中以变量的形式表示。
实际目的是在axes.annotate()
方法中使用这个,不过这里为了方便讨论,附上一段原理代码:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.05)
fig = plt.plot(x, x**2)
plt.grid(True)
g = 3
plt.xlabel(r'$test {}$'.format(g))
plt.show()
这是 OK.The g
的值传递给表达式。
但是,使用 \frac{}{}
和其他结构呢?
将上面的 xlabel()
字符串替换为:
plt.xlabel(r'$test \frac{1}{}$'.format(g))
给出:
IndexError: tuple index out of range
我知道使用花括号会发生一些事情,并且尝试了几个变体,但到目前为止没有任何效果。
花括号可以通过加倍来转义,但是 format 在替换 g 后删除了一对(并且 frac 期望它的参数在花括号中)所以你需要三对作为分母
plt.xlabel(r'$test \frac{{1}}{{{}}}$'.format(g))
您也可以使用“.replace()”方法绕过花括号方法
r'$\mathregular{T_{s1}}$'.replace('s1', 'toto')
产生
'$\mathregular{T_{toto}}$'
我想使用 LateX 格式构建一个表达式,其中出现了一些数字,但在 LateX 表达式中以变量的形式表示。
实际目的是在axes.annotate()
方法中使用这个,不过这里为了方便讨论,附上一段原理代码:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5, 5, 0.05)
fig = plt.plot(x, x**2)
plt.grid(True)
g = 3
plt.xlabel(r'$test {}$'.format(g))
plt.show()
这是 OK.The g
的值传递给表达式。
但是,使用 \frac{}{}
和其他结构呢?
将上面的 xlabel()
字符串替换为:
plt.xlabel(r'$test \frac{1}{}$'.format(g))
给出:
IndexError: tuple index out of range
我知道使用花括号会发生一些事情,并且尝试了几个变体,但到目前为止没有任何效果。
花括号可以通过加倍来转义,但是 format 在替换 g 后删除了一对(并且 frac 期望它的参数在花括号中)所以你需要三对作为分母
plt.xlabel(r'$test \frac{{1}}{{{}}}$'.format(g))
您也可以使用“.replace()”方法绕过花括号方法
r'$\mathregular{T_{s1}}$'.replace('s1', 'toto')
产生
'$\mathregular{T_{toto}}$'