1. 程式人生 > >linux 下matplotlib 無法顯示中文字型的問題

linux 下matplotlib 無法顯示中文字型的問題

# 小白的學習之路

僅僅記錄一下解決方案,有時間再整理一下解決問題的具體步驟和多種方法

網上的關於matplotlib 中文字型輸出問題大部分是基於windows作業系統,而且不能進行復現!!

不能進行復現的教程,不是一個好教程

@author:週末區捉魚點選開啟連結 https://blog.csdn.net/onepiece_dn/article/details/46239581

直接放出解決步驟:

   1.先看系統中的中文字型所在的位置

    $ fc-list  :lang=zh

/usr/share/fonts/truetype/arphic/uming.ttc: AR PL UMing TW MBE:style=Light
/usr/share/fonts/X11/misc/18x18ja.pcf.gz: Fixed:style=ja
/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc: Noto Sans CJK JP,Noto Sans CJK JP Bold:style=Bold,Regular
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai CN:style=Book
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai HK:style=Book
/usr/share/fonts/truetype/arphic/ukai.ttc: AR PL UKai TW:style=Book
/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc: Noto Sans Mono CJK KR,Noto Sans Mono CJK KR Bold:style=Bold,Regular
/usr/share/fonts/opentype/noto/NotoSansCJK-Black.ttc: Noto Sans CJK TC,Noto Sans CJK TC Black:style=Black,Regular
/usr/share/fonts/opentype/noto/NotoSansCJK-Black.ttc: Noto Sans CJK KR,Noto Sans CJK KR Black:style=Black,Regular
/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc: Noto Sans Mono CJK JP,Noto Sans Mono CJK JP Bold:style=Bold,Regular
/usr/share/fonts/opentype/noto/NotoSansCJK-Medium.ttc: Noto Sans CJK JP,Noto Sans CJK JP Medium:style=Medium,Regular
/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc: Noto Sans CJK JP,Noto Sans CJK JP Regular:style=Regular

           2.在python用絕對路徑來引用字型

import matplotlib.pyplot as plt
import matplotlib as mpl
zhfont= mpl.font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/ukai.ttc')
plt.plot([1, 2, 3])
plt.xlabel('x軸標籤', fontproperties=zhfont)
plt.ylabel('y軸標籤',fontproperties=zhfont)
plt.show()

   問題解決

     還有一個重疊字型序尋找程式碼,先放著裡,用到的時候再研究

from matplotlib.font_manager import FontManager
import subprocess
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)
output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True, encoding="utf8")
zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))

print('\n' + 'Chinese font list get from fc-list:')
for f in sorted(zh_fonts):
    print('\t' + f)
print('\n' + 'the fonts we can use:')
available = set(mpl_fonts) & set(zh_fonts)
for f in available:
    print('\t' + f)