简体   繁体   English

\\ text在matplotlib标签中不起作用

[英]\text does not work in a matplotlib label

I am using matplotlib together with latex labels for the axis, title and colorbar labels 我正在使用matplotlib和乳胶标签作为轴,标题和颜色条标签

While it works really great most of the time, it has some issues when you have a formula using \\text. 虽然它在大多数情况下都非常好用,但是当你使用\\ text时,它会有一些问题。

One really simple example. 一个非常简单的例子。

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,

Is there an easy way to use \\text in there? 有没有一种简单的方法在那里使用\\ text?

\\text won't work because it requires the amsmath package (not included in mathtext - the math rendering engine of matplotlib). \\text将无法工作,因为它需要amsmath包(不包含在mathtext中 - matplotlib的数学渲染引擎)。 So you basically have two options: 所以你基本上有两个选择:

  • use latex based font rendering 使用基于乳胶的字体渲染
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. use mathtext but use \\mathrm instead of \\text 使用mathtext但使用\\mathrm而不是\\text
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()

The latter approach creates a figure like 后一种方法创造了一个像 在此输入图像描述
Be aware that unlike with the \\text command, spaces inside the \\mathrm environment are not respected. 请注意,与\\text命令不同, \\mathrm环境中的空格不受尊重。 If you want more space between the variables you have to use latex style commands ( \\<space> , \\; , ...). 如果要在变量之间留出更多空间,则必须使用latex样式命令( \\<space>\\; ,...)。

One option is to let matplot lib use LaTeX directly for your text rendering (rather than the mathtext implementation that matplotlib provides). 一个选项是让matplot lib 直接使用LaTeX进行文本呈现(而不是matplotlib提供的mathtext实现)。

import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
# (create your plot as before)
plt.title(r"$f_{\mathrm{cor, r}}$")

This requires a fully working LaTeX installation. 这需要完全正常工作的LaTeX安装。 I can't seem to get it to recognise \\text , but \\mathrm does work (for 'roman family' font) just fine. 我似乎无法识别\\text ,但是\\mathrm确实有效(对于'罗马家族'字体)就好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM