【Python可视化】Matplotlib显示中文

导言

Matplotlib是一款强大的可视化工具,然而,其默认不支持中文的显示,其实,只要在显示的时候,指定好特定的中文字体,即可正常显示中文。

在下面的文件中,show_available_font 函数打印出可用的字体,然后根据返回的结果,在/usr/share/fonts 路径下进行搜索对应的库文件。其次,myfont = matplotlib.font_manager.FontProperties(fname=’/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf’) 用于加载该字体,plt.title(u’这里写的是中文’,fontproperties=myfont) 用于指定显示的字体。

# -*- coding: utf-8 -*-
""" Created on Wed Mar 16 15:54:17 2016 Linux 下,matplotlib显示中文。 @author: [email protected] """

from pylab import matplotlib,mpl
from matplotlib.font_manager import FontManager
import subprocess
import matplotlib.pylab as plt
import numpy as np

def show_available_font():
    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)
    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

def test():
    myfont = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf')
    mpl.rcParams['axes.unicode_minus'] = False
    pi = 3.1415926
    t = np.arange(-5*pi, 5*pi, 0.01)
    y = np.sin(t)/t
    plt.plot(t, y)
    plt.title(u'这里写的是中文',fontproperties=myfont) #指定字体
    plt.xlabel(u'X坐标',fontproperties=myfont)
    plt.ylabel(u'Y坐标',fontproperties=myfont)
    plt.show()

if __name__ == "__main__":
    show_available_font()
    test()

即可正常显示中文字体。
【Python可视化】Matplotlib显示中文_第1张图片

你可能感兴趣的:(可视化工具,python,可视化)