中文顯示問題
本地Mac上作圖,可以方便地實現中文字體顯示。比如在Jupter中,通過:
方法一:不下載字體庫即可實現中文顯示 (MAC)
plt.rcParams['font.family']=['Arial Unicode MS']
方法二:下載指定字體訓即可實現中文顯示
plt.rcParams['font.sans-serif'] = 'SimHei'
該方法需確保SimHei.ttf字體文件存在于:anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf
對于Linux系運行python代碼的畫圖腳本,則需要一些額外的配置。在此記錄詳細過程及細節提示,以供后續參考。
1.若安裝字體:
# Matplotlib中設置字體-黑體,解決Matplotlib中文亂碼問題
# 解決Matplotlib坐標軸負號'-'顯示為方塊的問題plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
另外seaborn
sns.set(font='SimHei') # Seaborn中設置字體-黑體,解決Seaborn中文亂碼問題
- 若未安裝字體
a.下載simhei.tff
b.查看位置
import matplotlib
print(matplotlib.matplotlib_fname())
/Users/bayes/anaconda3/envs/Env_3.6/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
cp ./simhei.ttf /Users/bayes/anaconda3/envs/Env_3.6/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
c.修改配置
vi /Users/bayes/anaconda3/envs/Env_3.6/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
font.family : sans-serif
#去掉前面的#
font.sans-serif : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#去掉前面的#,并在冒號后面添加SimHei
axes.unicode_minus : False
#去掉前面的#,并將True改為False
d.緩存位置
matplotlib.get_cachedir()
'/Users/bayes/.matplotlib'
rm -rf /Users/bayes/.matplotlib
e.重啟
3.各種字體大小
import matplotlib.pyplot as plt
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title