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

開元發表於2014-07-29

原因:matplotlib沒有使用作業系統的字型庫,同時預設的字型列表裡沒有可以顯示中文的字型。

解決過程:

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的字型目錄下,再重複以上步驟。

  • *對於Windows,沒有fc-list命令,找到對應可以字型直接在第2步裡修改也可。

相關文章