matplotlib設置宋體和Times New Roman體
寫論文時,要求圖中的中文字體為宋體,英文字體為Times New Roman體。
matplotlib默認是英文字體,如果設置中文的xlabel、ylabel或者title,顯示時會亂碼或者變成方塊,需要進行設置。
配置matplotlib
from matplotlib import rcParams
config = {
"font.family": 'serif', # 襯線字體
"font.size": 12, # 相當於小四大小
"font.serif": ['SimSun'], # 宋體
"mathtext.fontset": 'stix', # matplotlib渲染數學字體時使用的字體,和Times New Roman差別不大
'axes.unicode_minus': False # 處理負號,即-號
}
rcParams.update(config)
Ubuntu下的matplotlib添加中文支持
Windows環境下自帶宋體,而Ubuntu默認無中文字體支持,需要自己添加。
- 在Windows中找到SimSun字體文件,默認在
C:\Windows\Fonts\simsun.tcc
- 將該文件拷貝到Ubuntu的
/usr/share/matplotlib/mpl-data/fonts/ttf
目錄下(可能需要root權限) - 刪除當前用戶的matplotlib緩存:
cd ~/.cache/matplotlib && rm -rf *.*
- 關閉已打開的python解釋器,重新import matplotlib並按上面介紹的方法配置matplotlib即可
參考:
https://zhuanlan.zhihu.com/p/118601703
https://blog.csdn.net/jeff_liu_sky_/article/details/54023745