Skip to content Skip to sidebar Skip to footer

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 h

Solution 1:

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

Solution 2:

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

Post a Comment for "Get Positions Of Points In Pathcollection Created By Scatter()"