zoukankan      html  css  js  c++  java
  • Ubuntu下用matplotlib作图时显示中文

    之前在Ubuntu下用matplotlib作图的时候发现无法正常显示中文,查了一番以后发现是Ubuntu系统和matplotlib库没有共同可显示的中文字体库的原因。用此文章的方法可以解决这一问题。

    1.首先需要安装中文字体

    git clone https://github.com/tracyone/program_font && cd program_font && ./install.sh
    

    PS:文章中说需要删除matplotlib的缓存列表~/.cache/matplotlib/fontList.py3k.cache,但是在下并没有删,可能是这个原因导致之后文中的调用方法并没有起效而是换了一种。

    2.将安装的ttf字体文件复制到matplotlib的字体文件夹中(安装的ttf文件一般在/use/share/fonts/MyFonts/目录下)

    用matplotlib.matplotlib_fname()命令可以获取matplotlib的字体配置文件。比如在下的在如下位置/home/MyUserName/anaconda2/envs/tensorflow/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc.那么相应的字体目录在mpl-data/fonts/ttf下。

    cp /use/share/fonts/MyFonts/*.ttf /your/path/to/mpl-data/fonts/ttf/
    

    3.寻找matplotlib和Ubuntu都能用的中文字体 (原文源代码)

    __author__ = 'Katherine'
    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}
    "', shell=True)
    output = output.decode('utf-8')
    # print '*' * 10, '系统可用的中文字体', '*' * 10
    # print output
    zh_fonts = set(f.split(',', 1)[0] for f in output.split('
    '))
    available = mat_fonts & zh_fonts
    
    print('*' * 10, '可用的字体', '*' * 10)
    for f in available:
        print(f)
    

    输出为(基本是刚安装的中文字体):

    ********** 可用的字体 **********
    YouYuan
    SimHei
    YaHei Consolas Hybrid
    FangSong
    KaiTi
    Microsoft YaHei
    LiSu
    Yahei Mono
    

    4.配置matplotlib字体文件

    上面提到字体文件为matplotlibrc文件,编辑此文件找到font.family, font.serif, font.sans-serif行,删除句首#,然后将上述可用字体添加进去并用 , 隔开。例如:font.family: YouYuan, SimHei, FangSong, ...

    5.脚本中进行申明

    import pylab import mpl
    mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体,但在下运行的时候报了warning并没正常显示中文
    

    改用此方法则可行:

    from matplotlib.font_manager import FontProperties
    chinese_font = FontProperties(fname='/usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf')
    ...
    plt.text(x, y, display, fontsize=12, fontproperties=chinese_font)
    

    font_manager的用法可用看这里

    参考:

    1.How to Let Matplotlib Display Chinese Correctly
    3.https://monkey0105.github.io/posts/2016/Dec/15/matplotlib_chinese_display/#3rd,findavailableChinesefontsbothinmatplotlibandubuntu

  • 相关阅读:
    delete与double free
    OpenCV(1)——基础数据结构CvMat
    防止表单自动提交_随笔2012年5月16日
    Flex 学习笔记学习资料
    当析构函数遇到多线程 ── C++ 中线程安全的对象回调
    .NET Core2.0+MVC 用session,cookie实现的sso单点登录
    TreeView中右击直接获取节点的方法
    webservice 远程调试配置
    数组,集合 转成DataTable 方法
    String类中几个简单的常用方法
  • 原文地址:https://www.cnblogs.com/arkenstone/p/6411055.html
Copyright © 2011-2022 走看看