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

时间:2018-05-30 10:04:10

标签: python matplotlib tex

我使用matplotlib。我需要获得xlabels:[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()

1 个答案:

答案 0 :(得分:0)

您需要使用另一个卷曲括号来转义卷曲的括号({)。

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

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