Python 尝试使用getp检索matplotlib.lines.Line2D对象属性时出错
我有一个使用matplotlib.pyplot绘制的点的句柄列表,如下所示:Python 尝试使用getp检索matplotlib.lines.Line2D对象属性时出错,python,Python,我有一个使用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', markerfacecolo
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')
我还想从代码中其他地方的句柄(z[I].real和z[I].imag)中提取扩展数据和YData。但是,当我这样做时:
for i in range(1,len(zh)):
print zh[i]
zx = get(zh[i],'XData')
zy = get(zh[i],'YData')
我得到这个(第一行是上面“print zh[I]”的结果):
还是同样的错误:
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]
答案隐藏在--我希望这有帮助。我希望用户能够移动图形上绘制的点。z[i]是点在绘图中的初始位置。我需要保存一个指向该对象实例的指针,以便以后,一旦它被移动,我就可以检索新的扩展数据和YData。我一开始画的点正确吗?(我上面描述的在python中可能实现吗?)我发现我可能应该这样做:zx=plt.getp(z[i],'xdata'),尽管它仍然抱怨这是一个列表。我编辑了这篇文章,以包含问题的更简单版本。请参阅编辑部分。当我尝试以这种方式实例化其中一个时,我收到一个TypeError。它声称这是一个非类型的,因此不适合。你能把你的问题当作一个问题吗?显示您的代码,因为不清楚此代码段是否会导致您描述的错误。print plt.getp(new_handler)--并查看结果。newhandler是否包含您认为它的功能?这是否有助于您回溯查看问题?它返回“xdata=[0.5]”作为可能要检索的属性之一。请注意下面完全修改的解决方案。代码中有两个错误:(a)对
new\u handler
的赋值缺少逗号;(b)从Line2D
对象读取属性的方法使用get\u data()
方法,而不是getp
。非常感谢!真正让我困惑的是,这个错误显然是在抱怨新的\u处理程序是一个列表,但我不知道如何“转换”它,使它不再是一个列表。逗号是我一直在寻找的解决方案。有趣的是,这个错误(我认为是很常见的)也说明了python的一个缺点——因为变量类型没有显式定义,解释器可能会以一种意外的方式解释变量赋值!这是我将来一定要记住的。再次感谢。
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]