python Matplotlib绘图实现:中文宋体,英文新罗马(科研人必备);解决Font family [‘sans-serif‘] not found.

1、合并字体

将电脑自带的宋体和Times New Roman字体合并为新字体,我命名为SongNTR.ttf
https://github.com/nowar-fonts/Warcraft-Font-Merger(上述网站可以合并字体)
python Matplotlib绘图实现:中文宋体,英文新罗马(科研人必备);解决Font family [‘sans-serif‘] not found._第1张图片

2、将合并后的字体放置到matplotlib字体文件夹中

文件夹路径通过以下方式可以获得:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
 
print(matplotlib.matplotlib_fname())

输出路径:

c:\users\dell\appdata\local\programs\python\python38\lib\site-packages\matplotlib\mpl-data\matplotlibrc

python Matplotlib绘图实现:中文宋体,英文新罗马(科研人必备);解决Font family [‘sans-serif‘] not found._第2张图片

3、修改matplotlibrc文件

文件位于 C:\Users\dell\AppData\Local\Programs\Python\Python38\Lib\site-packages\matplotlib\mpl-data
打开后修改257行和265行,其中257行去掉注释,265行去掉注释并添加字体 SongNTR

font.family:  sans-serif
#font.style:   normal
#font.variant: normal
#font.weight:  normal
#font.stretch: normal
#font.size:    10.0

#font.serif:      DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif: SongNTR, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive:    Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive
#font.fantasy:    Chicago, Charcoal, Impact, Western, Humor Sans, xkcd, fantasy

python Matplotlib绘图实现:中文宋体,英文新罗马(科研人必备);解决Font family [‘sans-serif‘] not found._第3张图片

4、修改.matplotlib缓存文件 fontlist-v330.json

位于 C:\Users\dell.matplotlib
打开后插入以下内容:

{
      "fname": "fonts\\ttf\\SongNTR.ttf",
      "name": "SongNTR",
      "style": "normal",
      "variant": "normal",
      "weight": 700,
      "stretch": "normal",
      "size": "scalable",
      "__class__": "FontEntry"
    },

python Matplotlib绘图实现:中文宋体,英文新罗马(科研人必备);解决Font family [‘sans-serif‘] not found._第4张图片

4、重启python

5、测试

设置字体,实现中文:宋体,英文:Times New Roman

plt.rcParams['font.sans-serif'] = ['SongNTR'] ##设置字体

python Matplotlib绘图实现:中文宋体,英文新罗马(科研人必备);解决Font family [‘sans-serif‘] not found._第5张图片

参考:添加链接描述
添加链接描述

你可能感兴趣的:(matplotlib,python,开发语言)