matplotlib中的latex渲染
from matplotlib import rc
import matplotlib.pyplot as plt
rc('text', usetex=True)
plt.figure(figsize=(4, 3), dpi=120)
plt.plot([1, 2], [1, 2])
plt.title(r'$y=x$', fontsize=20)
plt.savefig('test.png')
plt.show()
usetex=True将matplotlib的文本渲染方式设置为latex。需要注意的是,matplotlib的latex有两个依赖,一个是tex,另一个是ghostscript。
- ghostscript的安装
$ brew install ghostscript
Error: Cannot write to /usr/local/Cellar
$ chown /usr/local
chown: /usr/local: Operation not permitted
/usr/local
在High Sierra系统不能被chown
sudo chown -R $(whoami) $(brew --prefix)/*
type1cm.sty error
LaTeX was not able to process the following string:'lp' Here is the full report generated by LaTeX: ...
! LaTeX Error: File `type1cm.sty' not found.
Type X to quit or
to proceed, or enter new name. (Default extension: sty)
l.3 \renewcommand
{\rmdefault}{pnc}^^M
No pages of output.
这时在texutil看type1cm.sty已经被安装了,查了一下是用extra组件解决的。
sudo port install texlive-latex-extra
最后在python脚本里配置路径,加入latex和ghostscript。
import os
os.environ["PATH"] += os.pathsep + '/usr/local/texlive/2017/bin/x86_64-darwin'
os.environ["PATH"] += os.pathsep + '/usr/local/Cellar/ghostscript/9.22/bin'
os.environ["PATH"] += os.pathsep + '/usr/local/bin'
os.getenv("PATH")
最后画图得到: