美文网首页
设置matplotlib显示中文

设置matplotlib显示中文

作者: 大聖Jonathan | 来源:发表于2018-01-25 10:34 被阅读0次

    本文参考:https://www.jianshu.com/p/15b5189f85a3 , 解决用matplotlib生成图表的时候,无法正常显示中文的问题

    下面是版本信息:

    • anaconda: Anaconda3-5.0.1-Windows-x86_64
    • python: 3.6.3
    • matplotlib:2.1.0

    matplotlib 默认不支持中文的显示,为了让其支持中文,需要具备两个条件:

    1. 系统中需要有中文字体文件,并且必须是ttf格式
    2. 告诉matplotlib去使用特定的字体,以支持显示中文

    本文以SimHei字体来说明具体的配置方法。可能Windows 10系统中带有这个字体(这里推荐一个Windows下好用的搜索工具:everything)。如果找不到这个字体,可以从 https://github.com/StellarCN/scp_zh/blob/master/fonts/SimHei.ttf 下载。

    matplotlib 会从matplotlibrc文件里读取配置文件。全局的配置文件存放在 \Anaconda3\Lib\site-packages\matplotlib\mpl-data\matplotlibrc 里,我们可以在用户根目录下创建一个matplotlibrc,该目录下的matplotlibrc优先级是高于全局的配置文件,因此我们可以在这里面定义使用的字体,具体步骤如下:

    1. 在用户的根目录,创建一个空白文件,命名为matplotlibrc

    2. 使用下面的命令,可以知道matplotlib读取的配置文件已经发生变化(如果没有步骤1,该命令会显示全局的配置路径)

      
      import matplotlib
      matplotlib.matplotlib_fname()
      
      >>> C:\\Users\\xxxxxx\\.matplotlib\\matplotlibrc
      
      
    3. 将SimHei字体文件(simhei.ttf)复制到 \Anaconda3\Lib\site-packages\matplotlib\mpl-data\fonts\ttf 目录下

    4. 用文本编辑器打开 C:\Users\xxxxxx.matplotlib\matplotlibrc,输入下面的代码(下面的代码中,解决了中文显示的问题和负号显示的问题)。matplotlib的默认font.family是使用sans-serif (sans-serif是属于一类字体),下面的代码指定了matplotlib将使用哪些字体,默认先会去找SimHei字体,如果找不到,接着找这个列表里的后一个,以此类推

      # 解决中文问题
      font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
      # 解决负号显示问题
      axes.unicode_minus  : False
      
    5. 重启Jupyter NoteBook,删除C:\Users\xxxxxx.matplotlib\下的tex.cache和fontList.json,这种matplotlib即可显示中文

    经过上面的步骤,如果依然无法显示中文,可尝试通过下面的代码排查:

    
    # 确保matplotlib读取的配置文件,是用户根目录下的matplotlibrc
    print(matplotlib.get_configdir())
    >>> C:\Users\lin.zhongsheng\.matplotlib
    
    # 确认一下,目前使用的font.family是
    from matplotlib.font_manager import findfont, FontProperties
    print(FontProperties().get_family())
    >>> ['sans-serif']
    
    # 确认一下,配置文件中font.sans-serif的值,与**步骤4**中定义的一致
    print(matplotlib.rcParams['font.sans-serif'])
    >>> ['SimHei', 'DejaVu Sans', 'Bitstream Vera Sans', 'Lucida Grande', 'Verdana', 'Geneva', 'Lucid', 'Arial', 'Helvetica', 'Avant Garde', 'sans-serif']
    
    # 确保可以找到SimHei的字体文件
    print(findfont(FontProperties(family=FontProperties().get_family())))
    >>> C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\mpl-data\fonts\ttf\simhei.ttf
    
    

    最后,我们还需要注意。即使配置好了,但在引入seaborn后,会再次出现乱码,那么可以在引入seaborn后,添加下面的代码解决

    
    import seaborn as sns
    sns.set_style({'font.sans-serif':['simhei','Arial']})
    
    

    相关文章

      网友评论

          本文标题:设置matplotlib显示中文

          本文链接:https://www.haomeiwen.com/subject/kynmaxtx.html