现象如下:
问题来源
利用matplotlib生成的图片,中文总是显示乱码
解决步骤:
情况①
有中文字体,在代码上直接加入下面的两行代码即可正常显示
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False ## 设置正常显示符号
情况②
在完成情况①的解决方法加上两行代码失败了
- 查找matplotlib字体安装路径
python
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/home/user/anaconda3/envs/gu_keras/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc'
2. 下载simhei.tff字体
下载’SimHei’
将字体保存在上述路径中mpl-data/fonts/tff的路径中
- 清除字体缓存
查看缓存路径
python
>>> import matplotlib
>>> matplotlib.get_cachedir()
复制路径,按 control-D退出python环境,输入一下命令删除缓存文件
rm -rf 路径
- 修改matplotlibrc文件
打开第一步中得到的路径中matplotlibrc文件,修改下面三个步骤
#font.family : sans-serif
去掉#改成
font.family : sans-serif
#font.serif : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New
去掉#且加上SimHei
font.serif : SimHei, DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New
#axes.unicode_minus : True
去掉#且将True改为False
axes.unicode_minus : False
可以尝试把.png改成.jpg试试看
Linux上修改代码
from matplotlib import pyplot as plt
from matplotlib import font_manager #font_manager设置中文
import matplotlib
#fname为计算机字体地址
my_font=font_manager.FontProperties(fname=‘C:\Windows\Fonts\SimHei.ttc’)
plt.figure(figsize=(20,8),dpi=80)
plt.xticks(list(range(max(b)+1))[::2])
plt.yticks(range(len(a)),a,fontproperties=my_font)
plt.barh(range(len(a)),b,height=0.6)
plt.xlabel(‘电影名称’,fontproperties=my_font)
plt.ylabel(‘票房’,fontproperties=my_font)
plt.title(‘电影票房汇总’,fontproperties=my_font)
可以搜索plt,如代码在后面加上
fontproperties=my_font