matplotlib为曲线添加legend却只显示框框【2022年12月】

检查是否加上英文逗号

最近在绘图时,碰到了这样一个问题,用 matplotlib 为曲线添加legend的时候发现只显示一个透明方框,添加注记的文字并没有预期展示。
请添加图片描述
经调查,出问题的代码部分,是在这:

# time domain
L1 = plt.plot(tt,data_shaped[0],'r')
L2 = plt.plot(tt,data_shaped[1],'b')
L3 = plt.plot(tt,data_shaped[2],'g')

# legend
plt.legend([L1, L2, L3],['Tx-Rx1', 'Tx-Rx2', 'Tx-Rx3'],loc = 'upper right')

解决方法是:在L1,L2,L3这三条曲线对象后加上英文逗号

即修改为

# time domain
L1, = plt.plot(tt,data_shaped[0],'r')
L2, = plt.plot(tt,data_shaped[1],'b')
L3, = plt.plot(tt,data_shaped[2],'g')

透明框就消失并正常显示注记文字了
请添加图片描述


注意设置中文环境

再补充一个之前就遇到过的问题,即 直接添加中文注记也是不行的,中文将只会以粗线框的形式显示

# time domain
L1, = plt.plot(tt,data_shaped[0],'r')
L2, = plt.plot(tt,data_shaped[1],'b')
L3, = plt.plot(tt,data_shaped[2],'g')

# legend
plt.legend([L1, L2, L3],['接收天线1', '接收天线2', '接受天线3'],loc = 'upper right')

请添加图片描述

这是因为matplotlib默认不支持中文,需在开头设置中文环境。即在开头新加入

import pylab as mpl

# 设置中文显示字体,因为matplotlib默认不支持中文
mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体为仿宋

之后也就能正常显示了:请添加图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值