0

Help me understand a little more about working with the matplot library of objects (which may really be a programming with Python question). This is a good example of the question. A comment says plot() command returning a list of objects:

"... plot returns a list of lines, so you need to get at the actual artist. You can either do line = ax.plot(x, y)[0] or do line, = ax.plot(x, y) which takes advantage of parameter unpacking." -- Is it possible to add a string as a legend item in matplotlib

But its not really a list of objects being returned, but wrapped up by another class,

(Pdb) p ax1
<matplotlib.axes.AxesSubplot object at 0x7fe4ba05e550>

I can't target the elements of the list in the normal way from the ax object:

(Pdb) ax1[0]
*** TypeError: 'AxesSubplot' object does not support indexing

What do I need to understand about objects in Python (jumping in between the classes--I've never seen fun(a,b)[0] before) to take advantage of what the comment is saying about the plot object returning a list?

Community
  • 1
  • 1
xtian
  • 2,765
  • 7
  • 38
  • 65

1 Answers1

0

I think you're just misreading that comment. If you have an AxesSubplot called ax1, and you run:

l = ax1.plot(x,y)

The type of l will be list (or some list-like object). The documentation for plot states this, too:

plot(*args, **kwargs)

Plot lines and/or markers to the Axes. args is a variable length argument, allowing for multiple x, y pairs with an optional format string.

...

Return value is a list of lines that were added.

So this:

line = ax.plot(x, y)[0]

Is just a shortcut for this:

lines = ax.plot(x, y)
line = lines[0]

It's not saying that the AxesSubplot object itself is a list, it's just saying that one of the instance methods of that object returns a list when you call it.

dano
  • 91,354
  • 19
  • 222
  • 219
  • It was there but I just didn't see it, **[** **]**. I've just never seen that shortcut before and it confused me. – xtian Jul 15 '14 at 20:42