When using matplotlib in Python, Chinese garbled characters are displayed _ (or change the font)

1. Problem description

        When using matplotlib to draw a visual chart, the Chinese of the chart displays garbled characters, and only English content can be displayed normally, as shown in the following figure:

2. Problem analysis

     Generally, the display of garbled characters is caused by encoding problems, and matplotlib uses ASCII encoding by default, but when using pyplot, it supports unicode encoding, but the default font is English, which makes Chinese characters cannot be displayed normally, so it displays Chinese garbled characters.

3. Solutions

Explanation: The environment I am currently using is [Python 3.11.1], [matplotlib 3.7.1] version

#查看python版本命令
python --version

#安装matplotlib命令:
pip install matplotlib

#查看当前安装的所有包和对应版本命令
pip list

 

  

3.1. Method 1 [Set global font]

"1" Import matplotlib and font dependent modules

from matplotlib import pyplot as plt
from matplotlib import font_manager

"2" View the fonts installed in the current system, so that you can use the font name in the global settings

fontnamelist = font_manager.get_font_names()
print(fontnamelist)

This is the name of all the fonts that come with the Windows 10 system 

['Harrington', 'STXinwei', 'Microsoft YaHei', 'Bookshelf Symbol 7', 'Edwardian Script ITC', 'Haettenschweiler', 'Franklin Gothic Demi', 'Niagara Engraved', 'cmr10', 'DejaVu Serif', 'Britannic Bold', 'Gigi', 'Microsoft JhengHei', 'French Script MT', 'Microsoft Uighur', 'YouYuan', 'Seagull: Paint v1.0', 'Baskerville Old Face', 'Times', 'Cooper Black', 'Tw Cen MT Condensed', 'Engravers MT', 'ITC Bookman', 'Brush Script MT', 'Calisto MT', 'Cambria', 'STSong', 'STIXSizeFourSym', 'SimSun', 'STXingkai', 'Informal Roman', 'Courier', 'Onyx', 'Segoe MDL2 Assets', 'SimSun-ExtB', 'OCR-A-Seagull', 'Verdana', 'Mongolian Baiti', 'Wingdings', 'FangSong', 'Playbill', 'Poor Richard', 'STHupo', 'Comic Sans MS', 'Curlz MT', 'STIXSizeThreeSym', 'Maiandra GD', 'Pristina', 'Agency FB', 'Gill Sans MT', 'Microsoft New Tai Lue', 'Tahoma', 'Bahnschrift', 'Script MT Bold', 'Albertus Extra Bold', 'CourierPS', 'Stencil', 'Microsoft Tai Le', 'Helvetica', 'Impact', 'Garamond', 'FZYaoTi', 'Franklin Gothic Heavy', 'Bell MT', 'Segoe Print', 'Book Antiqua', 'Lucida Fax', 'MS Outlook', 'Albertus Medium', 'Perpetua', 'Candara', 'Bodoni MT', 'CG Times', 'MS Reference Specialty', 'Papyrus', 'Juice ITC', 'ITC Avant Garde Gothic', 'cmsy10', 'Wingdings 2', 'FZShuTi', 'MS Gothic', 'Lucida Sans', 'Univers Condensed', 'HoloLens MDL2 Assets', 'cmmi10', 'BarCode', 'Rockwell Extra Bold', 'DengXian', 'Blackadder ITC', 'Rockwell', 'Matura MT Script Capitals', 'Perpetua Titling MT', 'Copperplate Gothic Light', 'Berlin Sans FB Demi', 'Old English Text MT', 'Wingdings 3', 'ITC Zapf Chancery', 'Consolas', 'Coronet', 'Eras Light ITC', 'STFangsong', 'Gadugi', 'cmss10', 'Lucida Bright', 'Century Gothic', 'Sitka Small', 'Seagull: Risk Phrases v1.0', 'Monotype Corsiva', 'OCR A Extended', 'Eras Bold ITC', 'STCaiyun', 'MT 
Extra', 'Letter Gothic', 'Footlight MT Light', 'STKaiti', 'Webdings', 'SymbolPS', 'Segoe UI Symbol', 'Yu Gothic', 'Malgun Gothic', 'Microsoft Sans Serif', 'Gill Sans MT Condensed', 'Bernard MT Condensed', 'Palatino Linotype', 'STIXNonUnicode', 'Snap ITC', 'DejaVu Sans Display', 'STIXGeneral', 'Kristen ITC', 'Helvetica Narrow', 'Franklin Gothic Medium', 'STIXSizeOneSym', 'Seagull: ADR v1.0', 'cmb10', 'Nirmala UI', 'Niagara Solid', 'Lucida Sans Unicode', 'Lucida Sans Typewriter', 'Vivaldi', 'STIXSizeTwoSym', 'Trebuchet MS', 'Broadway', 'KaiTi', 'Wide Latin', 'Tw Cen MT Condensed Extra Bold', 'Bradley Hand ITC', 'Centaur', 'cmex10', 'Eras Demi ITC', 'Kunstler Script', 'Century', 'Algerian', 'Vladimir Script', 'Franklin Gothic Book', 'Magneto', 'Modern No. 20', 'Felix Titling', 'Javanese Text', 'MV Boli', 'Segoe UI', 'Constantia', 'Segoe Script', 'Franklin Gothic Medium Cond', 'MingLiU-ExtB', 'Seagull: Electrical v1.0', 'STXihei', 'Courier New', 'Century Schoolbook', 'Microsoft PhagsPa', 'Viner Hand ITC', 'Forte', 'High Tower Text', 'Marigold', 'STLiti', 'Goudy Old Style', 'Harlow Solid Italic', 'Palace Script MT', 'Tw Cen MT', 'Ebrima', 'Eras Medium ITC', 'Seagull: Logos v1.0', 'Colonna MT', 'Gill Sans Ultra Bold Condensed', 'Franklin Gothic Demi Cond', 'Copperplate Gothic Bold', 'Georgia', 'SimHei', 'Seagull: Hazard v1.0', 'Gloucester MT Extra Condensed', 'OCR-B-Seagull', 'STZhongsong', 'Seagull: Emergency v1.0', 'Arial', 'Calibri', 'Ravie', 'Microsoft Himalaya', 'Seagull: Recycling v1.0', 'Seagull: Warning v1.0', 'Seagull: Textile Care v1.0', 
'Clarendon Condensed', 'DejaVu Sans', 'Bookman Old Style', 'New Century Schoolbook', 'Imprint MT Shadow', 'ITC Zapf Dingbats', 'STIXSizeFiveSym', 'Freestyle Script', 'Gill Sans Ultra Bold', 'Bauhaus 93', 'Leelawadee', 'Sylfaen', 'Dubai', 'Showcard Gothic', 'Rockwell Condensed', 'Univers', 'Rage Italic', 'Arial Rounded MT Bold', 'Gabriola', 'Mistral', 'Segoe UI Emoji', 'Leelawadee UI', 'Ink Free', 'Antique Olive', 'Palatino', 'DejaVu Serif Display', 'Berlin Sans FB', 'Lucida Console', 'Elephant', 'CG Omega', 'Tempus Sans ITC', 'Corbel', 'MS Reference Sans Serif', 'Jokerman', 'Parchment', 'Gill Sans MT Ext Condensed Bold', 'Castellar', 'LiSu', 'Lucida Handwriting', 
'Segoe UI Historic', 'Seagull: Packaging v1.0', 'Goudy Stout', 'Times New Roman', 'Symbol', 'DejaVu Sans Mono', 'Californian FB', 'Myanmar Text', 'cmtt10', 'Lucida Calligraphy', 'Chiller', 'Microsoft Yi Baiti']

 "3" set the global font

Set the global font to use the font that is already installed in the current system, for example, I use italics here

plt.rcParams['font.sans-serif']=['kaiti']

"4" solves the problem of "-" negative sign displaying garbled characters in the chart

plt.rcParams["axes.unicode_minus"]=False #解决图像中的"-"负号的乱码问题

"5" display effect

3.2. Method 2 [Setting local fonts]

"1" Import matplotlib and font dependent modules

from matplotlib import pyplot as plt
from matplotlib import font_manager

"2" View the fonts installed in the current system, so that you can use the font name in the global settings

fontnamelist = font_manager.get_font_names()
print(fontnamelist)

"3" set local font

 For example, here I have obtained the fonts of [Fake Song] and [Cai Ti]; and then set the corresponding fonts for the specified modules separately (that is: the title of the chart is in the font of Song Song, and the fonts displayed on the X and Y axes use it).

fangsong_font = font_manager.FontProperties(family="FangSong", size=20)
kaiti_font = font_manager.FontProperties(family="KaiTi", size=20)

plt.title("测试物体的平均值数据:",fontsize=18,fontproperties=fangsong_font)
plt.xlabel('当天时间',fontsize=16,fontproperties=kaiti_font)
plt.ylabel('平均数值',fontsize=16,fontproperties=kaiti_font)

 

3.3. Method 3 [Set the local font of the specified path]

"1" Import matplotlib and font dependent modules

from matplotlib import pyplot as plt
from matplotlib import font_manager

《2》Set the third-party fonts under the specified path

Note: the content after fname is the font under the specified path

siyuan_font = font_manager.FontProperties(fname = "fonts/SourceHanSansHWSC-Regular.otf",size=20)
simyou_font = font_manager.FontProperties(fname = "fonts/SIMYOU.TTF",size=20)


plt.title("测试物体的平均值数据:",fontsize=18,fontproperties=siyuan_font)
plt.xlabel('当天时间',fontsize=16,fontproperties=simyou_font)
plt.ylabel('平均数值',fontsize=16,fontproperties=simyou_font)

3.4. Method 4 [Set the global font of the specified path]

"1" Import matplotlib and font dependent modules

from matplotlib import pyplot as plt
from matplotlib import font_manager

"2" Add third-party fonts under the specified path

font_dirs = ["fonts"]  #fonts是当前程序下存放第三方字体的文件夹名称
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
for fontfile in font_files:
    font_manager.fontManager.addfont(fontfile)

 "3" View all font names currently owned

fontnamelist = font_manager.get_font_names()
print(fontnamelist)

"4" set the third-party font as the global font

plt.rcParams['font.sans-serif'] = ['Source Han Sans HW SC'] #设置全局字体(比如我这里添加的是思源宋体)

"5" display effect

3.5. References

Examples — Matplotlib 3.8.0.dev838+gbff46815c9 documentationhttps://matplotlib.org/devdocs/gallery/index.html

matplotlib.font_manager — Matplotlib 3.8.0.dev838+gbff46815c9 documentation https://matplotlib.org/devdocs/api/font_manager_api.html#matplotlib.font_manager.FontManager Matplotlib Chinese garbled solution (two ways) Matplotlib default font does not support Chinese, http://c.biancheng.net/matplotlib/9284.html

Guess you like

Origin blog.csdn.net/xiaochenXIHUA/article/details/130116221