擅长:python、mysql、java
<p>基于<a href="https://stackoverflow.com/a/40870637/2079386">the answer by EL_DON</a>,这里有一个用于绘制没有重复标签的图例的通用方法:</p>
<pre class="lang-py prettyprint-override"><code>def legend_without_duplicate_labels(ax):
handles, labels = ax.get_legend_handles_labels()
unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]
ax.legend(*zip(*unique))
</code></pre>
<p><em>示例用法:</em>(<a href="https://repl.it/@fonsf/unique-legend" rel="nofollow noreferrer">open in ^{<cd1>}</a>)</p>
<pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots()
ax.plot([0,1], [0,1], c="y", label="my lines")
ax.plot([0,1], [0,2], c="y", label="my lines")
legend_without_duplicate_labels(ax)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/b0TP4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b0TP4.png" alt="enter image description here"/></a></p>