2

我有一个使用 matplotlib.pyplot 绘制的点的句柄列表,如下所示:

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

我还想从代码中其他地方的句柄中提取 XData 和 YData(z[i].real 和 z[i].imag 到那时会改变)。但是,当我这样做时:

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

我明白了(第一行是上面“print zh[i]”的结果):

[<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'

编辑

我将问题简化为:

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

还是一样的错误:

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

1 回答 1

1

这是解决方案:

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]

答案隐藏在Line2D API 文档中——我希望这会有所帮助。

于 2012-06-02T15:05:21.603 回答