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
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]]
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.]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With