在matplotlib python中使用带有tex分数表达式的格式 [英] use format with tex fraction expression in matplotlib python

查看:392
本文介绍了在matplotlib python中使用带有tex分数表达式的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用matplotlib.我需要获取xlabel,例如:[1/8,2/8,3/8,4/8..14/8].我想使其循环.因此,为了获得更好的视图,我在Python中使用了TEX.为了在循环中呈现分数表达式,我使用了.format方法.但是它不能正常工作.在TEX中使用{}与.format方法之间存在一些冲突.我尝试使用double {},但是它也不起作用.

I use matplotlib. I need to get xlabels like: [1/8,2/8,3/8,4/8..14/8]. I want to make it in a loop. Therefore, for better view I use TEX in Python. For rendering the fraction expression in the loop I use .format method. But it doesn't work properly. There is some conflict between using of {} in TEX and .format method. I tried to use double {} but it as well doesn't work.

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

推荐答案

您需要使用另一个弯括号将弯括号({)逸出.

You need to escape the curled brackets ({) with another curled bracket.

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

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

Here the inner most bracket pair in {{{}}} is used for formatting. The escape pair {{ is replaced by a single bracket during formatting. Hence r'$\frac{{{}}}{{8}}$'.format(1) will result in r'$\frac{1}{8}$', which is then a valid MathText string.

这篇关于在matplotlib python中使用带有tex分数表达式的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆