[matplotlib] How to convert Chinese into Song typeface-English into New Roman typeface when drawing pictures

Some commonly used methods have been introduced on the Internet, and I have been tinkering with them for a long time, but they have not been successful. Finally, found a way to solve this problem.
Reference link: https://zhuanlan.zhihu.com/p/118601703, thanks for the article! Worship~

import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rcParams

matplotlib.use("pgf")
pgf_config = {
    
    
    "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.savefig('./图6-b.png',dpi=600)

insert image description here

Precautions:

  1. When running the code for the first time, it will install something similar to a plug-in. I didn’t pay attention to see what it is, and installed it directly.
  2. It seems that the file can only be saved in png format, tried jpg format without success.

Guess you like

Origin blog.csdn.net/qq_41821678/article/details/105804345