在matplotlib中显示外语(在虚拟环境中)

时间:2018-01-22 03:43:13

标签: matplotlib fonts jupyter

我在Jupyter中使用matplotlib,我的数据包括韩文字符。 Matplotlib还不支持韩文字符,所以建议我手动在matplotlib上设置字符。如果不设置字体,我的示例图将替换方形空框。

使用韩文字符的示例图。

objects = ('사과', '배', '귤', '오렌지', '바나나', '수박')
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Usage')
plt.title('Programming language usage')

plt.show()

enter image description here

在互联网上举几个例子,这就是我所做的。

  1. 下载韩文字体(.ttf)
  2. 复制我的字体目录中的字体('/ Users / Library / Fonts')
  3. 重新启动Jupyter内核并测试
  4. 我再次运行我的matplotlib以查看它是否会正确显示,但我仍然得到空盒子。

    这是我在Jupyter中运行的代码。

    from matplotlib import font_manager, rc
    font_name = font_manager.FontProperties(fname = '/Users/Library/Fonts/custom/NanumBarunGothic.ttf').get_name()    
    rc('font', family = font_name)
    

    这是错误信息。

    /Users/anaconda/envs/my_vir_env/lib/python3.4/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['NanumBarunGothic'] not found. Falling back to DejaVu Sans
      (prop.get_family(), self.defaultFamily[fontext]))
    

    所以这就是我认为我做错了。我没有把字体文件放在我的Jupyter的正确目录中,它在我的机器上的virenv上运行。我的问题是这个目录在哪里?我检查了'font_manager.py'文件,但我无法理解它。该文件说我的OS字体目录确实是

      

    用户/库/字体

    我感谢任何帮助! 提前谢谢!

1 个答案:

答案 0 :(得分:1)

事实证明这比我想象的要简单。如上所述@ImportanceOfBeingErnest,关键是:

  1. 安装字体
  2. 删除字体缓存
  3. 就我而言,我无法找到具有字体缓存的正确目录。我得到了post的帮助。

    1. 下载您想要的字体。将其放在字体目录中。就我而言,用户/图书馆/字体/...
    2. 找到字体缓存所在的目录。
    3. 在Jupyter中,在您的单元格中执行此操作。

      from matplotlib import font_manager
      fm = mpl.font_manager
      fm.get_cachedir()
      >> '/Users/.matplotlib'
      
      1. 然后转到该目录并删除文件
      2. 转到shell并执行此命令。

        rm fontList.py3k.cache
        

        现在当我执行matplotlib时,会显示正确的字体。