【问题标题】:use format with tex fraction expression in matplotlib python在matplotlib python中使用带有tex分数表达式的格式
【发布时间】:2018-11-09 03:26:21
【问题描述】:

我使用 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()

【问题讨论】:

  • {8}.format() 引起了问题。您可以将其留空并将8 作为第二个参数传递给format()。如:'$\frac{}{}$'.format(i, 8)
  • 不幸的是,它不起作用。它会产生错误ValueError: \frac18 ^ Expected \frac{num}{den}

标签: python matplotlib tex


【解决方案1】:

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

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

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

【讨论】:

  • 是的!有用!但是你能解释一下吗。这意味着 {{8}} 就像一对 {} 用于 TEX 使其成为分数,第二对用于 .format,但是 {{{}}} 呢?
  • 我添加了一些解释。
猜你喜欢
  • 1970-01-01
  • 2019-06-05
  • 2015-05-17
  • 1970-01-01
  • 2021-07-15
  • 2013-11-04
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多