Get ErrorbarContainer from legend

Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.array([1, 2])
y1 = np.array([1, 2])
y2 = np.array([1, 3])

ax.plot(x, y1, label='no error')
ax.errorbar(x, y2, yerr=np.array([.1, .1]), label='error')
ax.legend()
leg = ax.get_legend()

Now, if I do

ax.get_legend_handles_labels()

I get

([<matplotlib.lines.Line2D at 0x7fb773b827c0>,
  <ErrorbarContainer object of 3 artists>],
 ['no error', 'error'])

Is there a way to get the ErrorbarContainer directly from accessing an attribute of leg (say, if I couldn’t access ax directly)?

But you do have access to the legend object? If you have access to that then you can just do leg.axes to get the axes.

Hi @ianhi ,

Thanks for your reply. I’ll clarify my use case, as that doesn’t quite work for me.

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()

Say that I want to access the line which is currently displayed in the legend (i.e. the orange one). I could do

leg.legendHandles

but then that would give me a line without the marker info. Alternatively, if I do

leg.axes.get_legend_handles_lables()

then I get back both the error bar container and the (blue) line.

Sorry, I might not have asked very clearly - I’ve tried rephrasing and have posted to StackOverflow, see https://stackoverflow.com/q/66369388/4451315 , I’ll close here


sorry, am relatively new to discourse, looks like I can’t close this topic - in that case, I’m sorry for the noise / duplication

does leg.axes.get_legend_handles_labels()[0][1] give what you want? I think that all you have is a tuple of lists so normal indexing should work

Not quite, because I don’t know a-priori which index I will want. For example, if I have

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()

then I will want the orange and green lines (and not the blue one, which was plotted after the call to ax.legend).