plt.legend的相关用法
call signatures:
legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
Parameters:
handles:sequence of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
labels:list of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
调用签名对应于使用此方法的以下不同方式:
1.Automatic detection of elements to be shown in the legend
The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist:
ax.plot([1, 2, 3], label='Inline label')
ax.legend()
or
line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
ax.legend()
但是要注意:
通过使用以下划线“_”开头的标签,可以将特定艺术家从自动图例元素选择中排除。 以下划线开头的字符串是所有艺术家的默认标签,因此在不带任何参数且不手动设置标签的情况下调用 Axes.legend 将导致不绘制图例。
2.Explicitly listing the artists and labels in the legend
For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:
ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3.Explicitly listing the artists in the legend
This is similar to 2, but the labels are taken from the artists’ label properties. Example:
line1, = ax.plot([1, 2, 3], label='label1')
line2, = ax.plot([1, 2, 3], label='label2')
ax.legend(handles=[line1, line2])
4.Labeling existing plot elements
To make a legend for all artists on an Axes, call this function with an iterable of strings, one for each legend item. For example:
ax.plot([1, 2, 3])
ax.plot([5, 6, 7])
ax.legend(['First line', 'Second line'])
注意:This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up.