Linux下解決matplotlib中文亂碼的方法

緣由:matplotlib沒有使用操做系統的字體庫,同時默認的字體列表裏沒有能夠顯示中文的字體。python

解決過程:shell

1. 查看matplotlib支持的中文字體。

用python運行如下代碼:字體

#! /usr/bin/env python
# -*- coding: utf-8 -*-
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)
# 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

2. 配置matplotlibrc文件。

修改matplotlibrc文件(Ubuntu默認對應的是/etc/matplotlibrc):操作系統

font.family         : serif
font.serif : {zh_family}, serif

其中{zh_family}爲上一步中找到的其中一個可用中文字體。若是上步可用的字體爲空,則須要將中文字體文件(tff)複製到matplotlib的字體目錄下,再重複以上步驟。code

  • *對於Windows,沒有fc-list命令,找到對應能夠字體直接在第2步裏修改也可。
相關文章
相關標籤/搜索