2

Is there a way to get the x and y coordinates of scatter plot points from a Matplotlib Axes object? For plt.plot(), there is an attribute called data, but the following code does not work:

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'
Alex
  • 3,946
  • 11
  • 38
  • 66
  • For how to extract data from `PathCollection` object returned from `plt.scatter` see [Extracting data from a scatter plot in Matplotlib](https://stackoverflow.com/q/27849989/7851470) – Georgy May 22 '20 at 15:35

1 Answers1

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

Output is

[[ 1  2]
 [ 2  4]
 [ 6 10]
 [ 3  3]
 [11  2]]
Serenity
  • 35,289
  • 20
  • 120
  • 115