Python 添加图例出错:UserWarning: Legend does not support []


今天给图片添加图例时出现了上述错误

代码

    p=plt.plot(x, y, 'y', linewidth=1)
    plt.legend([p], ('label name'),loc='upper right')     
    plt.xlabel('time')              # label = name of label
    plt.ylabel('price')
    plt.title('Line Plot')
    plt.show()

解决方法

将p=plt.plot(x, y, ‘y’, linewidth=1)改为p,=plt.plot(x, y, ‘y’, linewidth=1),改完代码如下:

    p,=plt.plot(x, y, 'y', linewidth=1)
    plt.legend([p], ('label name'),loc='upper right')     
    plt.xlabel('time')              # label = name of label
    plt.ylabel('price')
    plt.title('Line Plot')
    plt.show()

解释是这样的:
The comma is Python syntax that denotes either a single-element tuple. E.g.,

>>> tuple([1])
(1,)

In this case, it is used for argument unpacking: plot returns a single-element list, which is unpacked into line:


>>> x, y = [1, 2]
>>> x
1
>>> y
2
>>> z, = [3]
>>> z
3

An alternative, perhaps more readable way of doing this is to use list-like syntax:


>>> [z] = [4]
>>> z
4

though the z,
= is more common in Python code.

逗号是用于解码。

你可能感兴趣的:(Python学习)