Ubuntu下用matplotlib作圖時顯示中文


之前在Ubuntu下用matplotlib作圖的時候發現無法正常顯示中文,查了一番以后發現是Ubuntu系統和matplotlib庫沒有共同可顯示的中文字體庫的原因。用此文章的方法可以解決這一問題。

1.首先需要安裝中文字體

git clone https://github.com/tracyone/program_font && cd program_font && ./install.sh

PS:文章中說需要刪除matplotlib的緩存列表~/.cache/matplotlib/fontList.py3k.cache,但是在下並沒有刪,可能是這個原因導致之后文中的調用方法並沒有起效而是換了一種。

2.將安裝的ttf字體文件復制到matplotlib的字體文件夾中(安裝的ttf文件一般在/use/share/fonts/MyFonts/目錄下)

用matplotlib.matplotlib_fname()命令可以獲取matplotlib的字體配置文件。比如在下的在如下位置/home/MyUserName/anaconda2/envs/tensorflow/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc.那么相應的字體目錄在mpl-data/fonts/ttf下。

cp /use/share/fonts/MyFonts/*.ttf /your/path/to/mpl-data/fonts/ttf/

3.尋找matplotlib和Ubuntu都能用的中文字體 (原文源代碼)

__author__ = 'Katherine'
from matplotlib.font_manager import FontManager
import subprocess

fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)

output = subprocess.check_output(
    'fc-list :lang=zh -f "%{family}\n"', shell=True)
output = output.decode('utf-8')
# print '*' * 10, '系統可用的中文字體', '*' * 10
# print output
zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))
available = mat_fonts & zh_fonts

print('*' * 10, '可用的字體', '*' * 10)
for f in available:
    print(f)

輸出為(基本是剛安裝的中文字體):

********** 可用的字體 **********
YouYuan
SimHei
YaHei Consolas Hybrid
FangSong
KaiTi
Microsoft YaHei
LiSu
Yahei Mono

4.配置matplotlib字體文件

上面提到字體文件為matplotlibrc文件,編輯此文件找到font.family, font.serif, font.sans-serif行,刪除句首#,然后將上述可用字體添加進去並用 , 隔開。例如:font.family: YouYuan, SimHei, FangSong, ...

5.腳本中進行申明

import pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默認字體,但在下運行的時候報了warning並沒正常顯示中文

改用此方法則可行:

from matplotlib.font_manager import FontProperties
chinese_font = FontProperties(fname='/usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf')
...
plt.text(x, y, display, fontsize=12, fontproperties=chinese_font)

font_manager的用法可用看這里

參考:

1.How to Let Matplotlib Display Chinese Correctly
3.https://monkey0105.github.io/posts/2016/Dec/15/matplotlib_chinese_display/#3rd,findavailableChinesefontsbothinmatplotlibandubuntu


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM