title: Roundtrip legend
body: <p>Here's a little code snippet:</p>
  <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
  
  fig, ax = plt.subplots()
  
  ax.errorbar([1, 2, 3], [1, 1, 1], yerr=[.1, .1, .1], c='orange', label='orange')
  ax.legend()
  ax.plot([1, 2, 3], [2, 2, 2], c='blue', label='blue')
  leg = ax.get_legend()
  </code></pre>
  <p>It looks like this:</p>
  <p><a href="https://i.stack.imgur.com/pc2qw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pc2qw.png" alt="enter image description here" /></a></p>
  <p>Now, if I was given <code>leg</code>, how could I recreate the legend?</p>
  <p>I have tried</p>
  <pre class="lang-py prettyprint-override"><code>ax.legend(leg.legendHandles, [i.get_text() for i in leg.get_texts()])
  </code></pre>
  <p>However, this doesn't preserve the maker info (notice how now the line in the legend is just a straight line, rather than a line with an error bar through it)</p>
  <p><a href="https://i.stack.imgur.com/mB6l8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mB6l8.png" alt="enter image description here" /></a></p>
  <p>I have also tried</p>
  <pre class="lang-py prettyprint-override"><code>ax.legend(*ax.get_legend_handles_labels());
  </code></pre>
  <p>however this adds a new line which wasn't visible in the original legend.</p>
  <p><a href="https://i.stack.imgur.com/BePs7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BePs7.png" alt="enter image description here" /></a></p>
  <hr />
  <h2>EDIT</h2>
  <p>If the original plot was</p>
  <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
  
  fig, ax = plt.subplots()
  
  ax.errorbar([1, 2, 3], [1, 1, 1], yerr=[.1, .1, .1], c='orange', label='orange')
  ax.plot([1, 2, 3], [3, 3, 3], c='green', label='green')
  ax.legend()
  ax.plot([1, 2, 3], [2, 2, 2], c='blue', label='blue')
  leg = ax.get_legend()
  </code></pre>
  <p>, which looks like this:
  <a href="https://i.stack.imgur.com/VK0Ct.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VK0Ct.png" alt="enter image description here" /></a></p>
  <p>then I would want to keep both the orange and the green lines. Basically, I want to keep only what's already visible in the legend, while <code>ax.get_legend_handles_labels</code> gives me everything back.</p>
  <h2>EDIT2</h2>
  <p>A 1-1 mapping between <code>leg.legendHandles</code> and <code>ax.get_legend_handles_labels()</code> would allow for this to be accomplished, can that be done?</p>