Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - ext does not work in a matplotlib label

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

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

One really simple example.

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

plt.show()

This will result in an error message like:

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

Is there an easy way to use ext in there?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ext 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:

  • 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 ext command
plt.plot([1,2,3])
plt.title(r"$f_{ext{cor, r}}$")
plt.show()
  1. use mathtext but use mathrm instead of ext
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 enter image description here
Be aware that unlike with the ext 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>, ;, ...).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...