\ text在matplotlib标签中不起作用 [英] \text does not work in a matplotlib label

查看:32
本文介绍了\ text在matplotlib标签中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 matplotlib 与乳胶标签一起用于轴、标题和颜色条标签

I am using matplotlib together with latex labels for the axis, title and colorbar labels

虽然大多数情况下它确实非常有效,但是当您使用\ text编写公式时,它会遇到一些问题.

While it works really great most of the time, it has some issues when you have a formula using \text.

一个非常简单的例子.

from matplotlib import pyplot as plt
plt.plot([1,2,3])
plt.title(r"$f_{\text{cor, r}}$")

plt.show()

这将导致错误消息,例如:

This will result in an error message like:

IPython/core/formatters.py:239: FormatterWarning: Exception in image/png formatter: 
f_{\text{1cor, r}}
   ^
Unknown symbol: \text (at char 3), (line:1, col:4)
  FormatterWarning,

有没有一种简单的方法可以在其中使用\ text?

Is there an easy way to use \text in there?

推荐答案

\ text 不起作用,因为它需要 amsmath 软件包(不包括在mathtext中-matplotlib 的数学渲染引擎).因此,您基本上有两个选择:

\text won't work because it requires the amsmath package (not included in mathtext - the math rendering engine of matplotlib). So you basically have two options:

  • 使用基于乳胶的字体渲染
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] #for \text command
plt.plot([1,2,3])
plt.title(r"$f_{\text{cor, r}}$")
plt.show()

  1. 使用mathtext,但使用 \ mathrm 而不是 \ text

来自matplotlib的

from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = False  # not really needed
plt.plot([1,2,3])
plt.title(r"$f_{\mathrm{cor, r}}$")
plt.show()

后一种方法可以创建一个像
请注意,与 \text 命令不同,\mathrm 环境中的空格不受重视.如果你想在变量之间有更多的空间,你必须使用乳胶风格的命令(\, \;, ...).

The latter approach creates a figure like
Be aware that unlike with the \text command, spaces inside the \mathrm environment are not respected. If you want more space between the variables you have to use latex style commands (\<space>, \;, ...).

这篇关于\ text在matplotlib标签中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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