matplotlib 中文问题

matplotlib的缺省配置文件中所使用的字体无法正确显示中文。为了让图表能正确显示中文,主要有三种设置中文的方法:

       (1)直接读取指定的字体文件。这种方法的依赖性最小,缺点是要指定字体文件的路径。举个例子,在源码所在目录下有STZHONGS.TTF字体文件,那么可以像下面这样写:

  1. # -*- coding: utf-8 -*-
    
    from numpy import *
    import matplotlib.pyplot as plt
    from matplotlib import font_manager
    
    # 如果要保存为pdf格式,需要增加如下配置
    #from matplotlib import rcParams
    #rcParams["pdf.fonttype"] = 42
    
    chf = font_manager.FontProperties(fname='STZHONGS.TTF')
    
    plt.plot(arange(0, 10, 1), arange(0, 10, 1))
    plt.title(u'中文测试图样', fontproperties=chf)
    plt.legend((u'图例',), 'lower right', prop=chf)
    plt.savefig('test.png', format='png')    # 或者pdf

    (2)在脚本里设置使用系统字体。这种方法要依赖于系统的字体文件。比如:

  2. # -*- coding: utf-8 -*-
    
    from numpy import *
    import matplotlib.pyplot as plt
    from matplotlib import rcParams
    
    rcParams['font.family'] = 'STZhongSong'
    
    # 如果要保存为pdf格式,需要增加如下配置
    #rcParams["pdf.fonttype"] = 42
    
    plt.plot(arange(0, 10, 1), arange(0, 10, 1))
    plt.title(u'中文测试图样')
    plt.legend((u'图例',), 'lower right')
    plt.savefig('test.png', format='png')    # 或者pdf

    (3)第三种方法是修改Matplotlib的默认配置,相当于把脚本里的设置移到了配置文件中。设置mpl-data\matplotlibrc文件,下面是默认的配置:

  3. #font.family         : sans-serif
    #font.serif          : Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
    #font.sans-serif     : Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

    如何获得自带的字体?

    在matplotlib中可以通过字体名指定字体,而每个字体名都与一个字体文件相对应。通过下面的程序可以获得所有可用的字体列表:

    >>> from matplotlib.font_manager import fontManager
    >>> fontManager.ttflist
    [<Font 'cmex10' (cmex10.ttf) normal normal 400 normal>,
     <Font 'Bitstream Vera Sans Mono' (VeraMoBd.ttf) normal normal 700 normal>,
     ...
    ]
    

    fontManager.ttflist是matplotlib的系统字体索引列表。其中的每个元素都是表示字体的Font对象。例如由第一个Font对象可知,字体名”cmex10”与字体文件“cmex10.ttf”相对应。下面的语句获得字体文件的全路径和字体名:

    >>> fontManager.ttflist[0].name
    'cmex10'
    >>> fontManager.ttflist[0].fname
    'C:\\Python26\\lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\cmex10.ttf'
    

    由字体文件的路径可知’cmex10’是matplotlib自带的字体。

    from matplotlib.font_manager import fontManager
    import matplotlib.pyplot as plt
    import os
    import os.path
    
    fig = plt.figure(figsize=(12,6))
    ax = fig.add_subplot(111)
    plt.subplots_adjust(0, 0, 1, 1, 0, 0)
    plt.xticks([])
    plt.yticks([])
    x, y = 0.05, 0.08
    fonts = [font.name for font in fontManager.ttflist if
        os.path.exists(font.fname) and os.stat(font.fname).st_size>1e6] ❶
    font = set(fonts)
    dy = (1.0-y)/(len(fonts)/4 + (len(fonts)%4!=0))
    for font in fonts:
        t = ax.text(x, y, u"中文字体", {'fontname':font, 'fontsize':14}, transform=ax.transAxes) ❷
        ax.text(x, y-dy/2, font, transform=ax.transAxes)
        x += 0.25
        if x >= 1.0:
            y += dy
            x = 0.05
    plt.show()

     

 

posted on 2015-11-19 11:31  月下之风  阅读(905)  评论(0编辑  收藏  举报

导航