1. Conventional solutions
Dynamically set matplotlibrc in the Python script, which can also avoid the trouble caused by changing the configuration file. The specific code is as follows:
from pylab import mpl
# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
Sometimes, after the font is changed, some characters in the coordinate axis will not be displayed normally. In this case, the parameters of axes.unicode_minus need to be changed:
# 设置正常显示符号
mpl.rcParams["axes.unicode_minus"] = False
The above solutions for general drawing can be solved, but I found that it cannot be solved under the ubuntu system
2. Solve in the ubuntu system
1. Download fonts simhei.ttf and simkai.ttf
Link: Baidu Cloud
Extraction code: i3pe
2. Upload the font to the server, upload location "/home/Downloads/fonts/"
For the server, you can use FileZilla to upload the file (refer to my previous blog Remote GPU Server Running Python_Dr.sky_'s Blog-CSDN Blog_Remote Server Running Python ), if you are local, you can directly copy it to the specified folder
3. Copy the font file to the specified folder, "/usr/share/fonts/truetype/noto/", other paths may be invalid
cd /home/Downloads/fonts
sudo cp -i simhei.ttf /usr/share/fonts/truetype/noto/
sudo cp -i simkai.ttf /usr/share/fonts/truetype/noto/
4. Delete the font path cache (it will be regenerated when running a new program)
cd /home/hao/.cache
rm -rf matplotlib
5. Add the following code to the script and run the program
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] #或者把"SimHei"换为"KaiTi"
matplotlib.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
Finally, restart the program to draw and display Chinese fonts