Reputation: 397
I need to get the x and y data for a point on a scatter plot. The issue is ultimately coming from the fact that when I create a scatter plot, there appears to be only one artist for all of the points. As such, when I try to get data from a PickEvent
, I get the same artist no matter which point I think I am picking, and that artist only has information for ALL of the points, not just the one I want:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(10)
y = np.random.rand(10)
def onpick(event):
print(event.artist.get_offsets())
plt.scatter(x,y, picker=5)
fig = plt.gcf()
cid_pick = fig.canvas.mpl_connect("pick_event", onpick)
Clicking on any of the points gives:
[[0.45112647259825556 0.4907629706037132]
[0.33787291043006795 0.5887038833531208]
[0.8199764461928875 0.9208354619124024]
[0.895372081518229 0.04417158362163531]
[0.684880991787429 0.7841477288024523]
[0.35336419403882413 0.4661111405652941]
[0.2931993381852086 0.9233951635623667]
[0.14585223675195036 0.1010652948995101]
[0.06953600296535056 0.7883191757749332]
[0.44078084770006243 0.6173437126304926]]
In THEORY I could just use a "button_press_event" to get the x and y data of where I click, but then I would have to do some sort of closest pair algorithm in order to associate it with the specific point, and that seems kind of over-kill for what seems like a common task. My question is if there is a more "built-in" way to do this?
Upvotes: 2
Views: 1038
Reputation: 30579
You can use event.ind
to index into the offsets you get from get_offsets()
:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(10)
y = np.random.rand(10)
def onpick(event):
print(event.artist.get_offsets()[event.ind][0])
plt.scatter(x,y, picker=5)
fig = plt.gcf()
cid_pick = fig.canvas.mpl_connect("pick_event", onpick)
Upvotes: 1