matplotlib:实现中文“宋体”,英文“Times New Rom”
操作系统是mac
- 安装simsun
- 下载字体SimHei.ttf SimSun.ttf
- 目录为/Users/xxx/.pyenv/versions/anaconda3-2020.02/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf
- 如果报错:Font family ['sans-serif'] not found,那么通过代码
import matplotlib matplotlib.get_cachedir()
找到缓冲文件目录,并删除之,然后重启jupyter,再然后修改/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc文件
font.family : sans-serif # 去掉前面的# font.sans-serif : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif # 去掉前面的#,并在冒号后面添加SimHei axes.unicode_minus : False # 去掉前面的#,并将True改为False
该部分参考了:https://blog.csdn.net/sinat_40875078/article/details/104326855
- 安装xelatex
- 下面示例代码应该就可以执行成功了
代码示例如下:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rcParams
matplotlib.use("pgf")
pgf_config = {
"pgf.texsystem": "xelatex",
"font.family":'serif',
"font.size": 7.5,
"pgf.rcfonts": False,
"text.usetex": True,
"pgf.preamble": [
r"\usepackage{unicode-math}",
r"\setmainfont{Times New Roman}",
r"\usepackage{xeCJK}",
r"\setCJKmainfont{SimSun}",
],
}
rcParams.update(pgf_config)
x = [1,2,3,4,5]
y = x
plt.figure()
# 坐标轴的刻度设置向内(in)或向外(out)
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
# 画图
plt.plot(x, y, '-o')
# 设置背景网格线为虚线
plt.grid(linestyle="--")
# 设置坐标轴标签
plt.xlabel("时间/s",fontsize=7.5)
plt.ylabel("角度/(°)",fontsize=7.5)
# 显示图像
plt.show()
plt.savefig('./a6-b.png',dpi=600)