请参阅下面的 MWE :
import matplotlib.pyplot as plt
import matplotlib.offsetbox as offsetbox
fig = plt.figure()
ax = fig.add_subplot(111)
text1 = r'$a\,=\,{}\pm{}$'.format(0.01, 0.002) # Works.
text2 = r'$a\;=\,{}\pm{}$'.format(0.01, 0.002) # Works.
text3 = r'$a\:=\,{}\pm{}$'.format(0.01, 0.002) # Does not work.
text = text3
ob = offsetbox.AnchoredText(text, pad=1, loc=6, prop=dict(size=13))
ob.patch.set(alpha=0.85)
ax.add_artist(ob)
plt.show()
虽然使用text1
和text2
间距的\,
和\;
可以正常运行,text3
使用\:
(即:位于between the previous two)的水平间距因ValueError
:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 42, in on_draw_event
self._render_figure(w, h)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 32, in _render_figure
backend_agg.FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 469, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1085, in draw
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2110, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1107, in draw
bbox = self.get_window_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1063, in get_window_extent
w, h, xd, yd = self.get_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1014, in get_extent
w, h, xd, yd = self.get_child().get_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 782, in get_extent
bbox, info, d = self._text._get_layout(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/text.py", line 320, in _get_layout
ismath=ismath)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 228, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/mathtext.py", line 3005, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/mathtext.py", line 2339, in parse
six.text_type(err)]))
ValueError:
a\:=\,0.01\pm0.002
^
Unknown symbol: \ (at char 1), (line:1, col:2)
为什么不能识别此乳胶间距?
答案 0 :(得分:7)
因为matplotlib使用mathtext作为默认数学渲染器。 Mathtext是常规TeX的子集。您可以使用完整的LaTeX:
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] #if needed
plt.plot([1,2,3])
plt.title(r"$a\:=\,{}\pm{}$".format(0.01, 0.002))
plt.show()