matplotlib adds legend to the curve but only displays the frame [December 2022]

Check if a comma is added

Recently, when drawing, I encountered such a problem. When I used matplotlib to add a legend to the curve, I found that only a transparent box was displayed, and the text added with the annotation was not displayed as expected.
Please add a picture description
After investigation, the problematic part of the code is here:

# 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')

The solution is: add a comma after the three curve objects L1, L2, L3

i.e. modified to

# 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')

The transparent frame disappears and the annotation text is displayed normally
Please add a picture description


Pay attention to setting the Chinese environment

Add another problem that I have encountered before, that is, it is not possible to directly add Chinese annotations, and Chinese will only be displayed in the form of thick lines .

# 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')

Please add a picture description

This is because matplotlib does not support Chinese by default, and the Chinese environment needs to be set at the beginning . i.e. at the beginning add new

import pylab as mpl

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

After that, it will be displayed normally:Please add a picture description

Guess you like

Origin blog.csdn.net/weixin_47305073/article/details/128348979