ubuntu下matplotlib畫圖中文亂碼問題

  最近由於論文緣由在學習機器學習,看的一本叫作《機器學習實戰》的書,看了看仍是不錯的,由於其中既有原理又有實例。今天載使用matplotlib進行畫圖時,發現中文會顯示爲小方塊,這個問題真是神煩,折騰了一下午,終於搞定了,下面記錄一下我解決的過程。python

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

    用python運行如下代碼:shell

#! /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

     我運行以後,發現說是"import Error:no module named font_manage"錯誤,以後通過一頓的搜索與嘗試,發現以下方法能夠解決這個問題:使用windows下的字體,講C:\windows\fonts文件夾下的全部以.ttf結尾的文件拷貝到/usr/share/fonts/truetype目錄下,並將全部的ttf文件的權限修改全部人能夠讀。segmentfault

    2. 配置matplotlibrc文件

    修改matplotlibrc文件(查詢該文件的方法:進入root跟目錄下,運行find -name matplotlibrc),修改成以下:windows

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

    其中{zh_family}就是1中所獲得的可用字體。機器學習

    參考資料

    【1】http://segmentfault.com/blog/defool/1190000000621721學習

    【2】http://www.zeuux.com/group/scipython/bbs/content/6270/字體

相關文章
相關標籤/搜索