Skip to main content
 首页 » 编程设计

python之尝试使用 getp 检索 matplotlib.lines.Line2D 对象属性时出错

2025年05月04日10JustinYoung

我有一个点的句柄列表,这些点是使用 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' 

请您参考如下方法:

解决方法如下:

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 documentation 中-- 我希望这会有所帮助。