【Python学习】Ubuntu16.04当中如何让matplotlib顺利显示中文


最近在帮一个朋友处理招考数据,需要使用matplotlib绘图,而绘图的图例需要加中文说明,因此,需要解决默认情况下,matplotlib无法显示中文的问题。
需要强调的是,本文测试的环境是 Ubuntu 16.04.4 LTS,本文测试的matplotlib库是通过conda命令安装的(如何使用conda管理python环境可以参考我的另外一篇博客 【Python学习】纯终端命令开始你的Anaconda安装与Python环境管理),也就是说,本文需要解决的问题具体为:Ubuntu16.04下的conda管理的python环境当中的matplotlib如何正确显示中文。

  • 本文用到的非代码之外的资源:

适用于Ubuntu16.04的simhei字体百度云链接
提取码:rxhd

1、明确你正在使用的matplotlib

在python当中使用以下代码获取你正在使用的matplotlib的字体设置文件位置

import matplotlib
matplotlib.matplotlib_fname()

以下是我的python返回的值:

'/home/lab-chen.yirong/anaconda2/envs/py36/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc'

那么,字体存储位置为:/home/lab-chen.yirong/anaconda2/envs/py36/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
需要修改的字体设置文件为:/home/lab-chen.yirong/anaconda2/envs/py36/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc

2、下载适用于Ubuntu16.04的simhei字体

适用于Ubuntu16.04的simhei字体百度云链接
提取码:rxhd
把该字体文件移动到.../matplotlib/mpl-data/fonts/ttf下,如下图为我使用WinSCP把文件从Windows发送到服务器上:
把simhei.ttf移动到相应位置

3、修改matplotlibrc文件

打开matplotlibrc文件文件的时候,可以看到,每一行都使用了#注释掉了代码,因此我们需要找到相对应的代码并且去掉注释,修改代码:

  • 文件的第162行左右会出现#### FONT,这提醒我们,接下来会出现相应的font设置,
    我把第198至213行的代码放到下面,可以看到,每一行都是灰色的(也就是被注释掉了):
#font.family         : sans-serif
#font.style          : normal
#font.variant        : normal
#font.weight         : normal
#font.stretch        : normal
## note that font.size controls default text sizes.  To configure
## special text sizes tick labels, axes, labels, title, etc, see the rc
## settings for axes and ticks. Special text sizes can be defined
## relative to font.size, using the following values: xx-small, x-small,
## small, medium, large, x-large, xx-large, larger, or smaller
#font.size           : 10.0
#font.serif          : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif     : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive        : Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive
#font.fantasy        : Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy
#font.monospace      : DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
  • 其中,我们需要修改font.familyfont.sans-serif这两个成员,一是要去掉注释,二是添加SimHei字体,修改后的代码如下:
font.family         : sans-serif
#font.style          : normal
#font.variant        : normal
#font.weight         : normal
#font.stretch        : normal
## note that font.size controls default text sizes.  To configure
## special text sizes tick labels, axes, labels, title, etc, see the rc
## settings for axes and ticks. Special text sizes can be defined
## relative to font.size, using the following values: xx-small, x-small,
## small, medium, large, x-large, xx-large, larger, or smaller
#font.size           : 10.0
#font.serif          : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif     : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive        : Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive
#font.fantasy        : Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy
#font.monospace      : DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace

保存后退出!

4、删除~/.cache/matplotlib/

  • 在终端进入~/.cache
cd ~/.cache/
  • 使用rm命令删除文件夹matplotlib/
rm -rf matplotlib/

5、关闭python内核,重新打开并运行代码

需要注意的是,在运行测试代码之前,建议先关闭python内核,也就是,如果正在打开Pycharm,就关掉它;如果正在打开jupyter notebook,也先关掉它。然后重新进入编译环境。
运行以下代码,观察是否能正常显示中文:

# 统计所在中学的申请人数选项
import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels = ['无', '10人及以下', '11人-20人', '21人-30人', '31人及以上']

men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.15  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='男')
rects2 = ax.bar(x + width/2, women_means, width, label='女')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

for l in ax.yaxis.get_ticklabels():
        l.set_family('SimHei')

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

fig.tight_layout()
plt.show()

我在jupyter notebook上运行的结果如下:
测试结果

【作者简介】陈艺荣,男,目前在华南理工大学电子与信息学院广东省人体数据科学工程技术研究中心攻读博士。曾获2次华南理工大学三好学生、华南理工大学“优秀共青团员”、新玛德一等奖学金(3000元,综测第3)、华为奖学金(5000元,综测第3)、汇顶科技特等奖学金(15000元,综测第1),两次获得美国大学生数学建模竞赛(MCM)一等奖,获得2016年全国大学生数学建模竞赛(广东赛区)二等奖、2017年全国大学生数学建模竞赛(广东赛区)一等奖、2018年广东省大学生电子设计竞赛一等奖等科技竞赛奖项,主持一项2017-2019年国家级大学生创新训练项目获得优秀结题,参与两项广东大学生科技创新培育专项资金、一项2018-2019年国家级大学生创新训练项目获得良好结题、4项华南理工大学“百步梯攀登计划”项目,发表SCI论文3篇授权实用新型专利5项,在受理专利17项(其中发明专利13项,11项进入实质审查阶段)。
我的Github
我的CSDN博客
我的Linkedin

发布了29 篇原创文章 · 获赞 252 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/m0_37201243/article/details/100706123
今日推荐