Matplotlib中文乱码的3种解决方案
前言
Matplotlib是一个Python2D绘图库,它可以在各种平台上以各种硬拷贝格式和交互式环境生成出具有出版品质的图形。Matplotlib可用于Python脚本,Python和IPythonshell,Jupyter笔记本,Web应用程序服务器和四个图形用户界面工具包。
然而最近在使用matplotlib默认情况会出现乱码问题,原则上matplotlib是支持中文的,只是在配置信息里没有中文字体的相关信息。
解决方法如下:
解决方案一:修改配置文件
matplotlib从配置文件matplotlibrc中读取配置,字体相关内容也在其中。查询当前matplotlibrc所在目录,可以用get_configdir()函数:
importmatplotlib 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 ##notethatfont.sizecontrolsdefaulttextsizes.Toconfigure ##specialtextsizesticklabels,axes,labels,title,etc,seetherc ##settingsforaxesandticks.Specialtextsizescanbedefined ##relativetofont.size,usingthefollowingvalues:xx-small,x-small, ##small,medium,large,x-large,xx-large,larger,orsmaller #font.size:10.0 #font.serif:DejaVuSerif,BitstreamVeraSerif,ComputerModernRoman,NewCenturySchoolbook,CenturySchoolbookL,Utopia,ITCBookman,Bookman,NimbusRomanNo9L,TimesNewRoman,Times,Palatino,Charter,serif #font.sans-serif:DejaVuSans,BitstreamVeraSans,ComputerModernSansSerif,LucidaGrande,Verdana,Geneva,Lucid,Arial,Helvetica,AvantGarde,sans-serif #font.cursive:AppleChancery,Textile,ZapfChancery,Sand,ScriptMT,Felipa,cursive #font.fantasy:ComicSansMS,Chicago,Charcoal,ImpactWestern,HumorSans,xkcd,fantasy #font.monospace:DejaVuSansMono,BitstreamVeraSansMono,ComputerModernTypewriter,AndaleMono,NimbusMonoL,CourierNew,Courier,Fixed,Terminal,monospace
matplotlib默认使用的font.family是sans-serif,即无衬线字体,可以看到在font.sans-serif中设置的全部为西文字体,这里的设置和css样式文件中设置差不多,只需要添加系统存在的字体名称即可(需要注意的是,matplotlib:
只支持ttf格式的字体),设置时需要将注释符号#去除。
解决方案二:重载配置文件
importmatplotlibasmpl mpl.rcParams['font.sans-serif']=['SimHei'] mpl.rcParams['font.serif']=['SimHei'] mpl.rcParams['axes.unicode_minus']=False#解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
解决方案三:自定义字体
importnumpyasnp importpylabaspl importmatplotlib.font_managerasfm 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()
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。