python用matplotlib作图时,中文标注显示乱码为小方框

使用matplotlib做图时,无法正确显示中文,乱码为小方框,主要是因为默认时,找不到字体.

/bin/env python 
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

x = np.arange(100, 600, 100)
train_1 = [11.8193, 28.0856, 36.3845, 62.8033, 95.7671]
train_2 = [70.8071, 242.193, 299.432, 377.331, 390.672]

plt.plot(x, train_pre_5, c='blue', marker='o', ms=4, label='精度<=10*e-5')
plt.plot(x, train_pre_6, c='red', marker='s', ms=4, label='精度<=10*e-6')
#plt.xticks(x)
plt.xlim(50, 550)
plt.ylim(-10, 410)
plt.xlabel('样本',fontproperties=font)
plt.ylabel('用时/s', fontproperties=font)
plt.savefig("./1.png")
plt.show()

运行上述代码,中文为小方框.
解决方法:
一:全局设置

import matplotlib as mpl
#配置之后便可使用
mpl.rcParams['font.family']='SimHei'
mpl.rcParams['font.sans-serif']=['SimHei']
mpl.rcParams['axes.unicode_minus']=False

二:局部设置

from matplotlib.font_manager import FontProperties 
font = FontProperties(fname=r"/usr/share/fonts/SIMLI.TTF")
plt.xlabel('样本',fontproperties=font)
plt.ylabel('用时/s', fontproperties=font)

由于图例plt.legend()要展示中文,此时得换用方法plt.legend(prop=my_font)

plt.legend(prop=font, loc="upper left")

其中,loc指定图例位置.

注:
ubuntu中部分中文字体缺失,所以可以从windows系统在中拷贝相关字体,但"c:\windows\fonts"下的字体,ttf文件为软连接,拷贝后无效,TTF文件可以使用.(暂没有找到好的解决办法)

参考:
1.
https://blog.csdn.net/yanpenggong/article/details/82730285
2.
https://blog.csdn.net/qq_44912982/article/details/107131711

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangxin0205

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值