Ser*_*lin 4 python matplotlib tex
我使用 matplotlib。我需要获得 xlabel,例如:[1/8,2/8,3/8,4/8..14/8]。我想把它做成一个循环。因此,为了更好地查看,我在 Python 中使用 TEX。为了在循环中渲染分数表达式,我使用 .format 方法。但它不能正常工作。在 TEX 中使用 {} 和 .format 方法之间存在一些冲突。我尝试使用 double {} 但它也不起作用。
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
xax = ax.xaxis # get x axis
labels = ['0']
for i in range(0, 14):
labels.append(r'$\frac{}{8}$'.format(i)) # when trying to insert i an error occurs
xax.set_ticklabels(labels)
plt.show()
Run Code Online (Sandbox Code Playgroud)
您需要用{另一个大括号转义大括号 ( )。
r'$\frac{{{}}}{{8}}$'.format(i)
Run Code Online (Sandbox Code Playgroud)
这里最里面的括号{{{}}}对用于格式化。在格式化过程中,转义对被替换{{为单个括号。因此r'$\frac{{{}}}{{8}}$'.format(1)将产生r'$\frac{1}{8}$',这是一个有效的 MathText 字符串。