matplotlib包默认只支持ASCII码,不支持unicode码。解决方法,就是在服务器matplotlib的matplotlibrc配置文件修改一下,将font.family
部分注释去掉,并且在font.serif 支持字体加上一个中文字体,如SimHei
以下代码可以查看系统支持哪些字体
from matplotlib.font_manager import FontManager
import subprocess
fm = FontManager()
mat_fonts = set(f.name for f in fm.ttflist)
print (mat_fonts)
output = subprocess.check_output(
'fc-list :lang=zh -f "%{family}\n"', shell=True)
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)
Pandas 中文乱码
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
如何系统内没有中文字体,可以下载一个在系统中安装并配置:
- 下载字体
下载地址:http://font.chinaz.com/130130474870.htm
解压rar文件。在 /usr/share/fonts 路径下创建存放此字体的文件夹yourfontdir,并将下载的ttf文件复制到yourfontdir中(可以给文件改个英文名,方便操作)
- 安装字体
cd /usr/share/fonts/yourfontsdir
#生成字体索引信息. 会显示字体的font-family
sudo mkfontscale
sudo mkfontdir
#更新字体缓存:
fc-cache
- 修改配置
修改文件配置,我的文件路径:/usr/local/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
# The font.size property is the default font size for text, given in pts.
# 12pt is the standard value.
#
font.family : serif
font.style : normal
font.variant : normal
font.weight : medium
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 : 12.0
font.serif : SimHei, Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
中文减号也显示方块,取消下面注释
axes.unicode_minus : True
将下载的ttf字体复制一份到以下路径
/usr/local/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
参考自:https://www.jianshu.com/p/7b7a3e73ef21