用pandas 或者 matplotlib 画图时,遇到中文时会显示出乱码

分析其原因,matplotlib 初始化时首先要加载配置文件,配置文件的名字叫 matplotlibrc,字体设置也在这个配置文件中,之所有无法正常显示中文是因为 matplotlib 默认不支持中文字体,解决的办法是我们需要在配置文件中指定一个 matplotlib 可用的中文字体。
在网站下载 SimHei 字体 ,该字体即有Windows字体也有Mac字体。下载后双击打开安装字体
http://www.fontpalace.com/font-details/SimHei/

找到 matplotlib 加载的配置文件路径可以通过如下方式:
[Python]
纯文本查看
复制代码
1 2 3 | >>> import matplotlib >>> matplotlib.matplotlib_fname() '/Users/<USERNAME>/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc' |
编辑 matplotlibrc 文件,找到 font.family 和 font.sans-serif 这两行,去掉注释,并添加 SimHei 字体到 font.sans-serif 中,如下:
[Bash shell]
纯文本查看
复制代码
1 2 | font.family : sans-serif font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif |
[Bash shell]
纯文本查看
复制代码
1 | rm -rf ~/.matplotlib |
第四步:重启jupyter notebook
如果你是在 ipython 环境下画图就重启 ipython,如果时 juypter notebook 画图 就重新 juypter notebook。
更多技术资讯可关注:itheimaGZ获取