当前位置: 移动技术网 > IT编程>脚本编程>Python > matplotlib 生成的图像中无法显示中文字符的解决方法

matplotlib 生成的图像中无法显示中文字符的解决方法

2020年06月23日  | 移动技术网IT编程  | 我要评论

俄罗那英,小杰的攻击,情定上海滩国语版

前几天使用matplotlib 绘图的时候发现无法使用中文字符,所以找了个笔记,顺便分享给大家

开发环境

  • windows 8.1 64bit
  • python 3.6.0
  • matplotlib 3.2.1

问题背景

使用 matplotlib 绘制函数图像的时候,发现设置图像名称或图例需要汉字显示的时候只能得到空格

生成图像中的中文错误效果

原因分析

python中的matplotlib仅支持unicode编码,默认是不显示中文的.

解决方案

解决方案1

python文件中添上一段语句

plt.rcparams['font.sans-serif']=['simhei']

之后再次运行得出图像 

解决方案2

制定加载本地的字体文件

在python文件中导入matplotlib的字体控制方法

from matplotlib.font_manager import fontproperties

另设font变量存储设置好的属性

font = fontproperties(fname=r'c:\windows\fonts\simhei.ttf',size=14)

设置 title 内容时将 font的存储对象赋给 fontproperties 属性

plt.title(u'y=x 与 y=x^0.5 的函数图像比较',fontproperties = font)

修改源码后生成的图像

附件

修改前的 python 文件

 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0,100) # 设置自变量的取值[0,100]

 y1 = x
 y2 = x**0.5

 plt.figure()
 plt.plot(x,y1,label='y=x')
 plt.plot(x,y2,label='y=x^0.5',color='red')

 plt.title('y=x 与 y=x^0.5 的函数图像比较')

 plt.legend()
 plt.show()

经解决方案1修改后的源码

 import numpy as np
 import matplotlib.pyplot as plt

 x = np.linspace(0,100) # 设置自变量的取值[0,100]

 y1 = x
 y2 = x**0.5

 plt.figure()
 plt.plot(x,y1,label='y=x')
 plt.plot(x,y2,label='y=x^0.5',color='red')

 plt.title('y=x 与 y=x^0.5 的函数图像比较')
 plt.rcparams['font.sans-serif']=['simhei']

 plt.legend()
 plt.show()

经解决方案2修改后的源码

 import numpy as np
 from matplotlib.font_manager import fontproperties
 import matplotlib.pyplot as plt

 x = np.linspace(0,100) # 设置自变量的取值[0,100]
 y1 = x
 y2 = x**0.5

 plt.figure()
 plt.plot(x,y1,label='y=x')
 plt.plot(x,y2,label='y=x^0.5',color='red')
 font = fontproperties(fname=r'c:\windows\fonts\simhei.ttf',size=14)

 plt.title(u'y=x 与 y=x^0.5 的函数图像比较',fontproperties = font)

 plt.legend()
 plt.show()

到此这篇关于matplotlib 生成的图像中无法显示中文字符的解决方法的文章就介绍到这了,更多相关matplotlib图像无法显示中文内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

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

相关文章:

验证码:
移动技术网