2016-07-25 277 views
2

有沒有辦法從Matplotlib Axes對象獲取散點圖點的x和y座標?對於plt.plot(),有一個名爲data的屬性,但下面的代碼不起作用:如何使用plt.gca()從matplotlib散點圖中獲取x和y座標?

x = [1, 2, 6, 3, 11] 
y = [2, 4, 10, 3, 2] 
plt.scatter(x, y) 
print(plt.gca().data) 
plt.show() 

--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
<ipython-input-30-9346ca31279c> in <module>() 
    41 y = [2, 4, 10, 3, 2] 
    42 plt.scatter(x, y) 
---> 43 print(plt.gca().data) 
    44 plt.show() 

AttributeError: 'AxesSubplot' object has no attribute 'data' 

回答

1
import matplotlib.pylab as plt 

x = [1, 2, 6, 3, 11] 
y = [2, 4, 10, 3, 2] 
plt.scatter(x, y) 
ax = plt.gca() 
cs = ax.collections[0] 
cs.set_offset_position('data') 
print cs.get_offsets() 

輸出是

[[ 1 2] 
[ 2 4] 
[ 6 10] 
[ 3 3] 
[11 2]] 
相關問題