Python: Ubuntu matplotlib 中文显示Python: Ubuntu matplotlib 中文显示Python: Ubuntu matplotlib 中文显示Python: Ubuntu matplotlib 中文显示
  • 首页
  • 博客
  • 书签
  • 文件
  • 分析
  • 登录

Python: Ubuntu matplotlib 中文显示

发表 admin at 2023年8月11日
类别
  • Python
标签

Post 1:

文章目录

  1. 1. 1st, install some Chinese fonts
  2. 2. 2nd, delete matplotlib cache list
  3. 3. 3rd, find available Chinese fonts both in matplotlib and ubuntu
  4. 4. 4th, find the directory of matplotlib font files
    1. 4.0.1. I copied /usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf to /home/katherine/anaconda3/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/.
  • 5. 5th, edit file matplotlibrc
  • 6. 6th, check the result
  • 7. Appendix
    1. 7.1. Method 1 - failed
    2. 7.2. Method 2 - succeeded, but annoyed, and cannot do anything with axis tick label
    3. 7.3. Method in Seaborn

本文介绍了好几种解决matplotlib中文显示问题的方法。

系统环境:

  • Ubuntu 16.04 LTS
  • Python3.5 virtual environment
  • jupyter notebook

1st, install some Chinese fonts

在ubuntu下执行以下命令即可完成安装。

git clone https://github.com/tracyone/program_font && cd program_font && ./install.sh

Source:

https://github.com/monkey0105/program_font

2nd, delete matplotlib cache list

Delete file ~/.cache/matplotlib/fontList.py3k.cache

Use Ctrl+h to unhide the hidden files.

3rd, find available Chinese fonts both in matplotlib and ubuntu

from matplotlib.font_manager import FontManager
import subprocess
fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
output = subprocess.check_output(
    'fc-list :lang=zh -f "%{family}\n"', shell=True)
output = output.decode('utf-8')
# print '*' * 10, '系统可用的中文字体', '*' * 10
# print output
zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))
available = mat_fonts & zh_fonts
print('*' * 10, '可用的字体', '*' * 10)
for f in available:
    print(f)
/home/katherine/venv/py35/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
/home/katherine/venv/py35/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
/home/katherine/venv/py35/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
/home/katherine/venv/py35/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')


********** 可用的字体 **********
YouYuan
KaiTi
SimHei
FangSong
YaHei Consolas Hybrid
Yahei Mono
Microsoft YaHei
LiSu

4th, find the directory of matplotlib font files

import matplotlib
matplotlib.matplotlib_fname()
'/home/katherine/venv/py35/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc'

If the output of the sentence above is

/home/katherine/anaconda3/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

Then the font file would be

/home/katherine/anaconda3/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/

If there is no available font in the output of 3rd step, you need to copy one into the font file directory.

I copied /usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf to /home/katherine/anaconda3/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/.

This font file stands for font named YaHei Consolas Hybrid.

5th, edit file matplotlibrc

font.family : {zh_family}, serif

font.serif : {zh_family}, ..., serif

font.sans-serif: {zh_family}, ...

Copy one available font name, e.g. YaHei Consolas Hybrid, to the place of {zh_family}.

6th, check the result

%matplotlib inline
# -*- coding:utf-8 -*-
from pylab import *
x = [2,4,6,8,10]
y = [1224,838,632,626,624]
xlabel(u"text for x轴")
ylabel(u"text for y轴")
title(u"x轴和Y轴对应关系")
plot(x,y)
savefig('test')
show()

Appendix

Method 1 - failed

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['YaHei Consolas Hybrid']
#plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
  
t = arange(-5*pi, 5*pi, 0.01)  
y = sin(t)/t  
plt.plot(t, y) 
plt.title(u'这里写的是中文')  
plt.xlabel(u'X坐标')  
plt.ylabel(u'Y坐标')  
plt.show()
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['YaHei Consolas Hybrid'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
  
t = arange(-5*pi, 5*pi, 0.01)  
y = sin(t)/t  
plt.plot(t, y)  
plt.title(u'这里写的是中文')  
plt.xlabel(u'X坐标')  
plt.ylabel(u'Y坐标')  
plt.show()

Method 2 - succeeded, but annoyed, and cannot do anything with axis tick label

from pylab import *  
myfont = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf')  
mpl.rcParams['axes.unicode_minus'] = False  
t = arange(-5*pi, 5*pi, 0.01)  
y = sin(t)/t  
plt.plot(t, y)  
plt.title(u'这里写的是中文',fontproperties=myfont) #指定字体  
plt.xlabel(u'X坐标',fontproperties=myfont)  
plt.ylabel(u'Y坐标',fontproperties=myfont)  
plt.show()

Method in Seaborn

This method may succeed after succeed in matplotlib, and may fail if not.

import seaborn as sns
sns.set(font='YaHei Consolas Hybrid')

 

Post 2:

之前在Ubuntu下用matplotlib作图的时候发现无法正常显示中文,查了一番以后发现是Ubuntu系统和matplotlib库没有共同可显示的中文字体库的原因。用此文章的方法可以解决这一问题。

1.首先需要安装中文字体

git clone https://github.com/tracyone/program_font && cd program_font && ./install.sh

PS:文章中说需要删除matplotlib的缓存列表~/.cache/matplotlib/fontList.py3k.cache,但是在下并没有删,可能是这个原因导致之后文中的调用方法并没有起效而是换了一种。

2.将安装的ttf字体文件复制到matplotlib的字体文件夹中(安装的ttf文件一般在/use/share/fonts/MyFonts/目录下)

用matplotlib.matplotlib_fname()命令可以获取matplotlib的字体配置文件。比如在下的在如下位置/home/MyUserName/anaconda2/envs/tensorflow/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc.那么相应的字体目录在mpl-data/fonts/ttf下。

cp /use/share/fonts/MyFonts/*.ttf /your/path/to/mpl-data/fonts/ttf/

3.寻找matplotlib和Ubuntu都能用的中文字体 (原文源代码)

__author__ = 'Katherine'
from matplotlib.font_manager import FontManager
import subprocess

fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)

output = subprocess.check_output(
    'fc-list :lang=zh -f "%{family}\n"', shell=True)
output = output.decode('utf-8')
# print '*' * 10, '系统可用的中文字体', '*' * 10
# print output
zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))
available = mat_fonts & zh_fonts

print('*' * 10, '可用的字体', '*' * 10)
for f in available:
    print(f)

输出为(基本是刚安装的中文字体):

********** 可用的字体 **********
YouYuan
SimHei
YaHei Consolas Hybrid
FangSong
KaiTi
Microsoft YaHei
LiSu
Yahei Mono

4.配置matplotlib字体文件

上面提到字体文件为matplotlibrc文件,编辑此文件找到font.family, font.serif, font.sans-serif行,删除句首#,然后将上述可用字体添加进去并用 , 隔开。例如:font.family: YouYuan, SimHei, FangSong, ...

5.脚本中进行申明

import pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体,但在下运行的时候报了warning并没正常显示中文

改用此方法则可行:

from matplotlib.font_manager import FontProperties
chinese_font = FontProperties(fname='/usr/share/fonts/MyFonts/YaHei.Consolas.1.11b.ttf')
...
plt.text(x, y, display, fontsize=12, fontproperties=chinese_font)

font_manager的用法可用看这里

 

Post 3:

解决matplotlib乱码问题 Windows系统

全部乱码

显示乱码如下:

RuntimeWarning: Glyph 22833 missing from current font.

直接使用很多博客中的方法,就是直接设置font.sans-serif和font.family等。

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['simhei']###解决中文乱码
plt.rcParams['axes.unicode_minus']=False

但是上面的这个方法只能解决,除了plt.legend以外的部分的乱码。因为还是有一部分有乱码

对于plt.legend部分标签中文乱码问题

解决了上述问题后,还是有其plt.legend`部分标签中文乱码问题。针对这个部分的乱码,我最终归结为,这个部分需要特殊处理,因此我添加了如下代码,下面的代码是全部包含的:

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

plt.rcParams['font.sans-serif'] = ['simhei']###解决中文乱码
plt.rcParams['axes.unicode_minus']=False

下面就是在使用plt.legend的时候,添加你的字体路径的相关了类型。注意这个目录下要有这个simhe=>simple character heiti 简体黑体字吧

my_font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf")
plt.legend(['精确度','损失'], loc=4,
               fontsize=8,prop=my_font)

Post 4:

Ubuntu 16.04 matplotlib 中文乱码

参考:

Linux 系统下 matplotlib 中文乱码解决办法

matplotlib图例中文乱码?

下载中文字体

simhei

存放

找到matplotlib字体存放位置

>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/home/zj/software/anaconda/anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc'

进入mpl-data/fonts/ttf文件夹,存放刚才下载的simhei.ttf

配置

可以全局配置,也可以局部配置

全局配置

在mpl-data有配置文件matplotlibrc,添加以下配置

font.family         : sans-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
axes.unicode_minus  : False
局部配置

在程序中配置使用中文字体

plt.rcParams['font.sans-serif']=['simhei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

重载

在文件头使用命令重载字体

from matplotlib.font_manager import _rebuild
_rebuild()  # reload一下

 

参考:

The following script to help check which fonts will work.

# -*- coding: utf-8 -*-
"""
Matplotlib font checker
Prints a figure displaying a variety of system fonts and their ability to produce Chinese text

@author: Mads Olsgaard, 2014

Released under BSD License.
"""

import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager

fonts = ['Droid Sans', 'Vera', 'TakaoGothic', 'TakaoPGothic', 'Liberation Sans', 'ubuntu', 'FreeSans', 'Droid Sans Japanese', 'DejaVu Sans']
#fonts = ['Arial', 'Times New Roman', 'Helvetica'] #uncomment this line on Windows and see if it helps!
english = 'The quick ...'
japanese = '中文'
x = 0.1
y = 1

# Buils headline
plt.text(x+0.5,y, 'english')
plt.text(x+0.7, y, 'Chinese')
plt.text(x,y, 'Font name')
plt.text(0,y-0.05, '-'*100)
y -=0.1

for f in fonts:
    matplotlib.rc('font', family='DejaVu Sans')
    plt.text(x,y, f+':')
    matplotlib.rc('font', family=f)
    plt.text(x+0.5,y, english)
    plt.text(x+0.7, y, Chinese)
    y -= 0.1
    print(f, font_manager.findfont(f))  # Sanity check. Prints the location of the font. If the font it not found, an error message is printed and the location of the fallback font is shown

plt.show()

On ubuntu the output should be the following:

Droid Sans /usr/share/fonts/truetype/droid/DroidSans.ttf
Vera /home/supermads/anaconda3/lib/python3.4/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf
TakaoGothic /usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf
TakaoPGothic /usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf
Liberation Sans /usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf
ubuntu /usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf
FreeSans /usr/share/fonts/truetype/freefont/FreeSans.ttf
Droid Sans Japanese /usr/share/fonts/truetype/droid/DroidSansJapanese.ttf
DejaVu Sans /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf

发表回复 取消回复

要发表评论,您必须先登录。

类别

  • Cat
  • Python
  • Django
  • Database
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • Maths/AI
  • PHP/Wordpress
  • Practice
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • SEO
  • English
  • Games
  • Recipes
  • General
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2023 艾丽卡 Blog support@alaica.com
      ajax-loader