Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get positions of points in PathCollection created by scatter()

If I create a scatterplot in matplotlib, how do I then get (or set) the coordinates of the points afterwards? I can access some properties of the collection, but I can't find out how to get the coordinates of the points themselves.

I can get as far as;

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

x = [0,1,2,3]
y = [3,2,1,0]

ax.scatter(x,y)

ax.collections[0].properties()

Which lists off all the properties of the collection, but I don't recognize any of them as being the coordinates

like image 246
C_Z_ Avatar asked Aug 25 '15 20:08

C_Z_


2 Answers

You can get the locations of the points, that is the original data you plotted, from a scatter plot by first setting the offsets to data coordinates and then returning the offsets.

Here's an example based on yours:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

x = [0,1,2,3]
y = [3,2,1,0]

ax.scatter(x,y)

d = ax.collections[0]

d.set_offset_position('data')

print d.get_offsets()

Which prints out:

[[0 3]
 [1 2]
 [2 1]
 [3 0]]
like image 67
Molly Avatar answered Oct 27 '22 01:10

Molly


Since set_offset_position is deprecated in in Matplotlib 3.3 (current version) here is another approach:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

x = [0, 1, 2, 3]
y = [3, 2, 1, 0]

points = ax.scatter(x, y)
print(points.get_offsets().data)

Which prints out:

[[0. 3.]
 [1. 2.]
 [2. 1.]
 [3. 0.]]
like image 34
Darío M. Avatar answered Oct 27 '22 02:10

Darío M.