Matplotlib中文亂碼解決方案
在使用matplotlib預設情況會出現亂碼問題,原則上matplotlib是支援中文的,只是在配置資訊裡沒有中文字型的相關資訊。
解決方案一:修改配置檔案
matplotlib 從配置檔案 matplotlibrc 中讀取配置,字型相關內容也在其中。查詢當前matplotlibrc 所在目錄,可以用 get_configdir()函式:
import matplotlib matplotlib.get_configdir()
通常存放位置:lib\site-packages\matplotlib\mpl-data\matplotlibrc
涉及到字型部分的設定內容為:
#font.family : sans-serif #font.style : normal #font.variant : normal #font.weight : normal #font.stretch : normal ## note that font.size controls default text sizes. To configure ## special text sizes tick labels, axes, labels, title, etc, see the rc ## settings for axes and ticks. Special text sizes can be defined ## relative to font.size, using the following values: xx-small, x-small, ## small, medium, large, x-large, xx-large, larger, or smaller #font.size : 10.0 #font.serif : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif #font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif #font.cursive : Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive #font.fantasy : Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy #font.monospace : DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
matplotlib 預設使用的 font.family 是 sans-serif,即無襯線字型,可以看到在font.sans-serif中設定的全部為西文字型,這裡的設定和css樣式檔案中設定差不多,只需要新增系統存在的字型名稱即可(需要注意的是,matplotlib:
只支援ttf格式的字型),設定時需要將註釋符號#去除。
解決方案二:過載配置檔案
import matplotlib as mpl mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['font.serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = False # 解決儲存影象是負號'-'顯示為方塊的問題,或者轉換負號為字串
解決方案三:自定義字型
import numpy as np import pylab as pl import matplotlib.font_manager as fm myfont = fm.FontProperties(fname=r'D:\Fonts\simkai.ttf') # 設定字型 t = np.arange(0.0,2.0 * np.pi,0.01) # 自變數取值範圍 s = np.sin(t) # 計算正弦函式值 z = np.cos(t) # 計算餘弦函式值 pl.plot(t,s,label='正弦') pl.plot(t,z,label='餘弦') pl.xlabel('x-變數',fontproperties=myfont,fontsize=24) #設定標籤 pl.ylabel('y-正弦餘弦函式值',fontproperties=myfont,fontsize=24) pl.title('sin-cos函式影象',fontproperties=myfont,fontsize=32) #影象標題 pl.legend(prop=myfont) pl.show()