stanri
stanri

Reputation: 2972

Error when attempting to retrieve a matplotlib.lines.Line2D object property using getp

I have a list of handles to points that have been plotted using matplotlib.pyplot like so:

import matplotlib.pyplot as plt
...

for i in range(0,len(z)):
    zh[i] = plt.plot(z[i].real, z[i].imag, 'go', ms=10)
    plt.setp(zh[i], markersize=10.0, markeredgewidth=1.0,markeredgecolor='k', markerfacecolor='g')

I'd also like to extract the XData and YData from the handles somewhere else in the code (z[i].real and z[i].imag would have changed by then). However, when I do this:

for i in range(1,len(zh)):
    print zh[i]
    zx = get(zh[i],'XData')
    zy = get(zh[i],'YData')

I get this (first line is a result of the "print zh[i]" above):

[<matplotlib.lines.Line2D object at 0x048FDA70>]

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
  return self.func(*args)
...
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 1130, in getp
  func = getattr(obj, 'get_' + property)
AttributeError: 'list' object has no attribute 'get_XData'

EDIT

I simplified the problem down to this:

new_handler = plt.plot(0.5, 0, 'go', ms=10)
plt.setp(new_handler, markersize=10.0, markeredgewidth=1.0,markeredgecolor='k',markerfacecolor='g',picker=5)
print plt.getp(new_handler,'xdata')

Still same error:

AttributeError: 'list' object has no attribute 'get_xdata'

Upvotes: 2

Views: 47133

Answers (1)

daedalus
daedalus

Reputation: 10923

Here is the solution:

import matplotlib.pyplot as plt

# plot returns a list, therefore we must have a COMMA after new_handler
new_handler, = plt.plot(0.5, 0, 'go', ms=10)

# new_handler now contains a Line2D object
# and the appropriate way to get data from it is therefore:
xdata, ydata = new_handler.get_data()
print xdata

# output:
# [ 0.5]

The answer was hidden in the Line2D API documentation -- I hope this helps.

Upvotes: 1

Related Questions