Python matplotlib中的LaTeX:由.format()定义的变量下标

Python matplotlib中的LaTeX:由.format()定义的变量下标,python,matplotlib,latex,Python,Matplotlib,Latex,我正在创建一个子图数组,其中每个项都在for循环中定义。对于每个子批次,ylabel以LaTeX作为变量名写入(比如\theta),子索引由循环中的计数器定义。写入plt.ylabel(r'$\theta{:2d}$'.format(i))中的命令.format()允许指定索引 但是,当计数器的位数超过1位时,ylabel中变量的下标仅适用于第一位,其余的则以内联方式写入。在使用.format()时,我是否有误解?还是有别的办法解决这个问题 例如: import numpy as np imp

我正在创建一个子图数组,其中每个项都在for循环中定义。对于每个子批次,
ylabel
以LaTeX作为变量名写入(比如
\theta
),子索引由循环中的计数器定义。写入
plt.ylabel(r'$\theta{:2d}$'.format(i))
中的命令
.format()
允许指定索引

但是,当计数器的位数超过1位时,
ylabel
中变量的下标仅适用于第一位,其余的则以内联方式写入。在使用
.format()
时,我是否有误解?还是有别的办法解决这个问题

例如:

import numpy as np

import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 22})
matplotlib.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
matplotlib.rcParams['text.usetex'] = True

N     = 500
theta = np.random.randn(90,N)
idx   = np.array([4,24,64,89])
nplot = len(idx) 

fig, axes = plt.subplots(nplot, 1, sharex='col', figsize=(10, 5))
axes      = axes.flatten()
for i in range(nplot):
    ax = axes[i]
    ax.plot(theta[idx[i],:], '-', color='navy')
    ax.set_ylabel(r'$\theta_{:2d}$'.format(idx[i]+1))
    ax.set_xlim([0,N])
plt.show()
显示问题的结果图如下所示:


您需要将格式更改为:

ax.set_ylabel(r'$\theta{{{{:2d}}}}$'格式(idx[i]+1))

LaTeX希望格式为
\theta_{somenumber}
,否则它将仅下标第一个数字。要实现这一点,Python中需要3个方括号。

我尝试使用2个方括号,但没有效果,没想到Python需要3个方括号。非常感谢。