Solve the problem of using matplotlib to output Chinese garbled characters

When I put the code that runs well in Windows into the Linux system, an error that the corresponding font cannot be found will be reported, and the output pictures will also be garbled. Through searching for information, we know that many Windows fonts are not supported on Linux. You need to use fonts suitable for Linux.
These are the well-known open source fonts for Linux that I found through searching for information.
WenQuanYi Micro Hei: An open source font that provides Chinese character support.
Source Han Serif: A set of open source Chinese fonts that supports simplified and traditional characters.
Source Han Sans: A set of open source Chinese fonts that supports simplified and traditional characters.
AR PL New Sung: A free Chinese font that provides Song style glyphs. insert image description here
If you want to check which fonts are supported by your operating system, you can check it with the following code:

fc-list :lang=zh

insert image description here
It should not have been here before. I have downloaded the relevant fonts. If you need to download, you can install the font with the following command.

sudo yum install wqy-microhei-fonts

Below I will demonstrate with Wenquanyi Weihei font:
If you want to know which language you have, you can check it by running the following Python code:

from matplotlib.font_manager import FontManager
 
mpl_fonts = set(f.name for f in FontManager().ttflist)
 
print('all font list get from matplotlib.font_manager:')
for f in sorted(mpl_fonts):
    print('\t' + f)

insert image description here
Here we see the WenQuanYi Micro Hei font, which is the font we installed before.

# 设置中文字体
plt.rcParams['font.sans-serif'] = 'WenQuanYi Micro Hei'

By setting it to a supported font, you can run the code normally.
insert image description here
References:
https://blog.csdn.net/kuwola/article/details/122409200
https://blog.51cto.com/welcomeweb/5539966
https://www.cnblogs.com/houfei/p/13489409.html

Guess you like

Origin blog.csdn.net/biyn9/article/details/131181527