我正在使用 matplotlib 绘制电流。我想使用 EngFormatter 格式化 y 轴。
yformatter = mtick.EngFormatter(unit="A")
ax.yaxis.set_major_formatter(yformatter)
当电流在微安范围内并且 EngFormatter 必须绘制 µ 时,如果我使用 tex,它会给出错误。
mpl.rc("text", usetex=True)
这是相关的追溯:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
600 else:
601 # use dviread. It sometimes returns a wrong descent.
--> 602 dvifile = self.make_dvi(tex, fontsize)
603 with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
604 page = next(iter(dvi))
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\texmanager.py in make_dvi(self, tex, fontsize)
383
384 if DEBUG or not os.path.exists(dvifile):
--> 385 texfile = self.make_tex(tex, fontsize)
386 command = [str("latex"), "-interaction=nonstopmode",
387 os.path.basename(texfile)]
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\texmanager.py in make_tex(self, tex, fontsize)
298 else:
299 try:
--> 300 fh.write(s.encode('ascii'))
301 except UnicodeEncodeError as err:
302 mpl.verbose.report("You are using unicode and latex, but "
UnicodeEncodeError: 'ascii' codec can't encode character '\u03bc' in position 234: ordinal not in range(128)
是否有针对此错误的解决方法?
请您参考如下方法:
如果您阅读 texmanager.py 中的完整代码段,您会发现:
if rcParams['text.latex.unicode']:
fh.write(s.encode('utf8'))
else:
try:
fh.write(s.encode('ascii'))
except UnicodeEncodeError as err:
_log.info("You are using unicode and latex, but have not "
"enabled the 'text.latex.unicode' rcParam.")
raise
您应该看到它们同样被您的程序记录下来。 如果你阅读 the documentation ,它告诉您相同的解决方案:启用 text.latex.unicode。
matplotlib.rcParams['text.latex.unicode'] = True
