解决ubantu系统下matplotlib中文乱码问题
目录
一、安装中文字体
二、在代码中配置
三、结果展示
参考链接:
Ubuntu下让matplotlib显示中文字体_ubuntu matplot 使用汉字-CSDN博客
一、安装中文字体
git clone https://github.com/tracyone/program_font
cd program_font
./install.sh
之后便可以在自己/usr/share/fonts/MyFonts目录下看到很多字体。
二、在代码中配置
font_path = "/usr/share/fonts/MyFonts/simhei.ttf" # 替换成你的字体路径
myfont = fm.FontProperties(fname=font_path)plt.rcParams['axes.unicode_minus'] = False # 避免坐标轴负号乱码
在需要使用中文字体的地方,如legend。最后的prop=myfoot比较关键。
legend_elements = [Line2D([0], [0], marker='o', color='w', markerfacecolor='g', label='未分配起点', markersize=8),Line2D([0], [0], marker='o', color='w', markerfacecolor='r', label='未分配终点', markersize=8),Line2D([0], [0], marker='^', color='g', label='正在执行起点', markersize=8),Line2D([0], [0], marker='x', color='r', label='正在执行终点', markersize=8),Line2D([0], [0], marker='o', color='b', label='机器人', markersize=8)]plt.legend(handles=legend_elements, loc='upper right', prop=myfont)