在 matplotlib 中使用带有 tex 分数表达式的格式 python

use format with tex fraction expression in matplotlib python

我使用 matplotlib。我需要像这样的 xlabels:[1/8,2/8,3/8,4/8..14/8]。我想让它循环。因此,为了更好地查看,我在 Python 中使用 TEX。为了在循环中呈现分数表达式,我使用 .format 方法。但它不能正常工作。在 TEX 中使用 {} 和 .format 方法之间存在一些冲突。我尝试使用双 {} 但它也不起作用。

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()

您需要用另一个大括号转义大括号 ({)。

r'$\frac{{{}}}{{8}}$'.format(i)

此处{{{}}}中最里面的括号对用于格式化。转义对 {{ 在格式化期间被单个括号替换。因此 r'$\frac{{{}}}{{8}}$'.format(1) 将导致 r'$\frac{1}{8}$',这是一个有效的 MathText 字符串。