【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發送到服務器上:
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.family
和font.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