Python使用matplotlib時顯示中文亂碼解決方法(或更改字體)
一、問題描述
在使用matplotlib繪制可視化圖表時,圖表的中文顯示亂碼,只能正常顯示英文內(nèi)容,如下圖所示:
二、問題分析
一般顯示亂碼是由于編碼問題導(dǎo)致的,而matplotlib 默認(rèn)使用ASCII 編碼,但是當(dāng)使用pyplot時,是支持unicode編碼的,只是默認(rèn)字體是英文字體,導(dǎo)致中文無法正常顯示,所以顯示中文亂碼。
三、解決方法
說明:我當(dāng)前使用的環(huán)境是【Python 3.11.1】、【matplotlib 3.7.1】版本
#查看python版本命令 python --version #安裝matplotlib命令: pip install matplotlib #查看當(dāng)前安裝的所有包和對應(yīng)版本命令 pip list
3.1、方法一【設(shè)置全局的字體】
《1》導(dǎo)入matplotlib和字體依賴模塊
from matplotlib import pyplot as plt from matplotlib import font_manager
《2》查看當(dāng)前系統(tǒng)已經(jīng)安裝的字體,方便在全局設(shè)置中使用字體名稱
fontnamelist = font_manager.get_font_names() print(fontnamelist)
這是獲取到的Windows10系統(tǒng)自帶所有字體的名稱
['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》設(shè)置全局字體
設(shè)置全局字體使用的是當(dāng)前系統(tǒng)已經(jīng)安裝的字體,比如我這里使用的是楷體
plt.rcParams['font.sans-serif']=['kaiti']
《4》解決圖表中"-"負(fù)號顯示亂碼問題
plt.rcParams["axes.unicode_minus"]=False #解決圖像中的"-"負(fù)號的亂碼問題
《5》 展示效果
3.2、方法二【設(shè)置局部字體】
《1》導(dǎo)入matplotlib和字體依賴模塊
from matplotlib import pyplot as plt from matplotlib import font_manager
《2》查看當(dāng)前系統(tǒng)已經(jīng)安裝的字體,方便在全局設(shè)置中使用字體名稱
fontnamelist = font_manager.get_font_names() print(fontnamelist)
《3》設(shè)置局部字體
比如我這里是獲取了【仿宋】、【楷體】的字體;然后在單獨給指定的模塊設(shè)置對應(yīng)字體(即:圖表標(biāo)題是仿宋字體,而X和Y軸上顯示的則使用楷體字體)。
fangsong_font = font_manager.FontProperties(family="FangSong", size=20) kaiti_font = font_manager.FontProperties(family="KaiTi", size=20) plt.title("測試物體的平均值數(shù)據(jù):",fontsize=18,fontproperties=fangsong_font) plt.xlabel('當(dāng)天時間',fontsize=16,fontproperties=kaiti_font) plt.ylabel('平均數(shù)值',fontsize=16,fontproperties=kaiti_font)
3.3、方法三【設(shè)置指定路徑的局部字體】
《1》導(dǎo)入matplotlib和字體依賴模塊
from matplotlib import pyplot as plt from matplotlib import font_manager
《2》設(shè)置指定路徑下的第三方字體
注意:fname后面的內(nèi)容是指定路徑下的字體
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("測試物體的平均值數(shù)據(jù):",fontsize=18,fontproperties=siyuan_font) plt.xlabel('當(dāng)天時間',fontsize=16,fontproperties=simyou_font) plt.ylabel('平均數(shù)值',fontsize=16,fontproperties=simyou_font)
3.4、方法四【設(shè)置指定路徑的全局字體】
《1》導(dǎo)入matplotlib和字體依賴模塊
from matplotlib import pyplot as plt from matplotlib import font_manager
《2》添加指定路徑下的第三方字體
font_dirs = ["fonts"] #fonts是當(dāng)前程序下存放第三方字體的文件夾名稱 font_files = font_manager.findSystemFonts(fontpaths=font_dirs) for fontfile in font_files: font_manager.fontManager.addfont(fontfile)
《3》查看當(dāng)前擁有的所有字體名稱
fontnamelist = font_manager.get_font_names() print(fontnamelist)
《4》設(shè)置第三方的字體為全局字體
plt.rcParams['font.sans-serif'] = ['Source Han Sans HW SC'] #設(shè)置全局字體(比如我這里添加的是思源宋體)
《5》展示效果
3.5、參考資料
- Examples — Matplotlib 3.8.0.dev838+gbff46815c9 documentation:https://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中文亂碼解決方案(兩種方式)Matplotlib 默認(rèn)字體并不支持中文,http://c.biancheng.net/matplotlib/9284.html
總結(jié)
到此這篇關(guān)于Python使用matplotlib時顯示中文亂碼解決方法(或更改字體)的文章就介紹到這了,更多相關(guān)matplotlib顯示中文亂碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 深度學(xué)習(xí)中的4種激活函數(shù)
這篇文章主要介紹了python深度學(xué)習(xí)中的4種激活函數(shù),幫助大家更好的進行深度學(xué)習(xí),感興趣的朋友可以了解下2020-09-09淺談Pycharm調(diào)用同級目錄下的py腳本bug
今天小編就為大家分享一篇淺談Pycharm調(diào)用同級目錄下的py腳本bug,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12PyQt5每天必學(xué)之QSplitter實現(xiàn)窗口分隔
這篇文章主要介紹了PyQt5每天必學(xué)之窗口分隔,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04網(wǎng)絡(luò)瀏覽器中運行Python腳本PyScript剖析
這篇文章主要為大家介紹了網(wǎng)絡(luò)瀏覽器中運行Python腳本PyScript剖析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08