Skip to main content
 首页 » 编程设计

python之如何使用 plt.gca() 从 matplotlib 散点图中获取 x 和 y 坐标

2025年04月02日15unruledboy

有没有办法从 Matplotlib Axes 对象获取散点图点的 x 和 y 坐标?对于plt.plot(),有一个名为data的属性,但是下面的代码不起作用:

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' 

请您参考如下方法:

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]]