在matplotlib中,解决中文乱码问题

#!/usr/bin/env python3
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
font = FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=14)
#将(0,10)分成等区间的100份
x=np.linspace(0,10,100)
#在matplotlib中使用数学函数的方法
y=np.sin(x)
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(x,y)
ax.set_title('正弦函数图',fontproperties=font)

plt.show()

这里采用的是matplotlib中的font_manager方法:

(1)先导入font_manager

from matplotlib.font_manager import FontProperties
(2)找到中文字体在电脑中的位置
font = FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=14)
(3)解决问题:

ax.set_title('正弦函数图',fontproperties=font)
效果如图所示:


拓展:如果图例中出现了乱码就这么修改:

plt.legend(prop=font)


猜你喜欢

转载自blog.csdn.net/DM_learner/article/details/79446292
今日推荐