python:使用matplotlib画图时,中文乱码的问题

中文乱码:

错误信息:RuntimeWarning: Glyph 23398 missing from current font.

解决方案:

1、下载字体simhei.ttf

 

2、查找字体路径和字体缓存路径:

import matplotlib

# 查找字体路径
print(matplotlib.matplotlib_fname())
# 查找字体缓存路径
print(matplotlib.get_cachedir())

结果:

/Users/apple/opt/anaconda2/envs/python37/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc
/Users/apple/.matplotlib

 

3、将下载好的字体文件,存放到目录:(根据上面的结果,找到字体存放位置)

/Users/apple/opt/anaconda2/envs/python37/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf

 

4、修改/Users/apple/opt/anaconda2/envs/python37/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc文件:

 font.family         : sans-serif   
 # 去掉前面的#     
 font.sans-serif     : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif  
 # 去掉前面的#,并在冒号后面添加SimHei
 axes.unicode_minus  : False
 # 去掉前面的#,并将True改为False

 

5、删除缓存:

rm -rf /Users/apple/.matplotlib

 

6.重启 IDE

 

案例源码:

# coding:utf-8
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

# # 查找字体路径
# print(matplotlib.matplotlib_fname())
# # 查找字体缓存路径
# print(matplotlib.get_cachedir())

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.serif'] = ['SimHei']

filename = './files/datatemplate4.xlsx'
students = pd.read_excel(filename)
students.sort_values(by='Number', inplace=True, ascending=False)
print(students)
# students.plot.bar(x='Students', y='Number', color='blue', title='成绩统计')
plt.bar(students.Students, students.Number, color='blue')
plt.xticks(students.Students, rotation='90')
plt.xlabel('Students')
plt.ylabel('Number')
plt.title('成绩统计')
plt.tight_layout()
plt.show()

 

数据文件格式:

 

posted @ 2020-03-06 15:54  KeenLeung  阅读(1737)  评论(0编辑  收藏  举报