<jupyter_start><jupyter_text>Matplotlib legend 图例 如何添加一个图例 方法 11. 通过`matplotlib.pyplot.plot`的属性`label`进行设置图里名称1. 使用`plt.legend(handles=[line...])`向图中加入图例<jupyter_code>import matplotlib.pyplot as plt
a, = plt.plot([1,2,3], label='line a')
plt.legend(handles=[a])

plt.show()<jupyter_output><empty_output><jupyter_text>方法 2- 官方文档: https://matplotlib.org/api/_as_gen/matplotlib.patches.Patch.htmlmatplotlib.patches.Patch- 通过`mpatches.Patch.Patch`进行设置图例内容<jupyter_code>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()<jupyter_output><empty_output><jupyter_text>方法3<jupyter_code>import matplotlib.lines as mlines

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                          markersize=15, label='Blue stars')
plt.legend(handles=[blue_line])

plt.show()<jupyter_output><empty_output><jupyter_text>图例的位置- 官方文档: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.htmlmatplotlib.pyplot.legend- 通过`matplotlib.pyplot.legend`的`bbox_to_anchor`+`loc`属性设置    - 比如 `loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)`      bbox_to_anchor- 参数为(x, y, width, height) 或(x, y) loc 属性值| Location String | Location Code || --------------- | ------------- || 'best'          | 0             || 'upper right'   | 1             || 'upper left'    | 2             || 'lower left'    | 3             || 'lower right'   | 4             || 'right'         | 5             || 'center left'   | 6             || 'center right'  | 7             || 'lower center'  | 8             || 'upper center'  | 9             || 'center'        | 10            |<jupyter_code>plt.subplot(211)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")

# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc='best', borderaxespad=0.)

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17402945113788487, 'fraction_numerical': 0.02989736724676484, 'mean_word_length': 3.3365570599613155, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '125653', 'license': 'Apache-2.0', 'n_tokens_mistral': 932, 'n_tokens_neox': 871, 'n_words': 156, 'path': 'doc/matplotlib/legend.ipynb', 'repo_name': 'huifer/python_doc', 'size': '2241'}