当前位置: 移动技术网 > IT编程>脚本编程>Python > Matplotlib中文乱码的3种解决方案

Matplotlib中文乱码的3种解决方案

2018年11月30日  | 移动技术网IT编程  | 我要评论

本乡奏多丑闻,gatitaya,名侦探柯南日语中字

前言

matplotlib是一个python 2d绘图库,它可以在各种平台上以各种硬拷贝格式和交互式环境生成出具有出版品质的图形。 matplotlib可用于python脚本,python和ipython shell,jupyter笔记本,web应用程序服务器和四个图形用户界面工具包。

然而最近在使用matplotlib默认情况会出现乱码问题,原则上matplotlib是支持中文的,只是在配置信息里没有中文字体的相关信息。

解决方法如下:

解决方案一:修改配置文件

matplotlib 从配置文件 matplotlibrc 中读取配置,字体相关内容也在其中。查询当前matplotlibrc 所在目录,可以用 get_configdir()函数:

import matplotlib
matplotlib.get_configdir()

通常存放位置:lib\site-packages\matplotlib\mpl-data\matplotlibrc

涉及到字体部分的设置内容为:

#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

matplotlib 默认使用的 font.family 是 sans-serif,即无衬线字体,可以看到在font.sans-serif中设置的全部为西文字体,这里的设置和css样式文件中设置差不多,只需要添加系统存在的字体名称即可(需要注意的是,matplotlib:

只支持ttf格式的字体),设置时需要将注释符号#去除。

解决方案二:重载配置文件

import matplotlib as mpl
mpl.rcparams['font.sans-serif'] = ['simhei']
mpl.rcparams['font.serif'] = ['simhei']
mpl.rcparams['axes.unicode_minus'] = false # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串

解决方案三:自定义字体

import numpy as np
import pylab as pl
import matplotlib.font_manager as fm

myfont = fm.fontproperties(fname=r'd:\fonts\simkai.ttf') # 设置字体
t = np.arange(0.0,2.0 * np.pi,0.01) # 自变量取值范围
s = np.sin(t) # 计算正弦函数值
z = np.cos(t) # 计算余弦函数值
pl.plot(t,s,label='正弦')
pl.plot(t,z,label='余弦')
pl.xlabel('x-变量',fontproperties=myfont,fontsize=24) #设置标签
pl.ylabel('y-正弦余弦函数值',fontproperties=myfont,fontsize=24)
pl.title('sin-cos函数图像',fontproperties=myfont,fontsize=32) #图像标题
pl.legend(prop=myfont)
pl.show()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网