matplotlib在ubuntu下中文显示解决办法

matplotlib在ax.set_title中可以使用定义FontProperties来实现,首先定义

myfont = matplotlib.font_manager.FontProperties(
fname='/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc'
)

然后在ax.set_title中作为参数fontproperties = myfont调用字体。

这样的好处是直接调用系统字体,不用受字体是ttf还是ttc的限制。

但在ax.bar中这种方式因为无法使用参数而无效,网上有很多种解决汉字显示的办法,总结一下,可以使用两种方式解决。

首先需要下载ttf字体,比如文泉驿的微米黑字体,然后查看matplotlib的配置文件

import matplotlib
matplotlib.matplotlib_fname()

将字体上传到python3.6/site-packages/matplotlib/mpl-data下的fonts/ttf文件夹中

方式一

修改python3.6/site-packages/matplotlib/mpl-data下的matplotlibrc文件,将里面的

#font.family :sans-serif
#font.sans-serif : wqy-mircohei,SimHei, DejaVu Serif……(把文泉驿文件名如wqy-microhei加到最前面)
#axes.unicode_minus,将True改为False (这里是关于负号显示的,也可以在程序中设置)

然后删除当前用户下.cache/matplotlib目录下的所有文件,其实就是fontlist-v300.json文件。

重启后文字显示正常。

方式二:

直接修改fontlist-v300.json文件

首先找到文泉驿的字典选项,将原先为?的文件名改为wqy-microhei,然后将defaultFamily改为文泉驿字体名字,defaultFont路径修改为文泉驿字体所在。

重启后文字显示正常,两种方法都不再需要定义调用FontProperties

Leave a Reply

您的电子邮箱地址不会被公开。 必填项已用 * 标注

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>