中文亂碼:
錯誤信息: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()
數據文件格式: