9

I have a simple scatter plot with a picker event.
I want to change the color of the data point I click with mouse.
The code I have will change the color of the whole array.
How can I just change one particular point?

import sys
import numpy as np
import matplotlib.pyplot as plt    
testData = np.array([[0,0], [0.1, 0], [0, 0.3], [-0.4, 0], [0, -0.5]])
    fig, ax = plt.subplots()
    sctPlot, = ax.plot(testData[:,0], testData[:,1], "o", picker = 5)
    plt.grid(True)
    plt.axis([-0.5, 0.5, -0.5, 0.5])

def on_pick(event):
    artist = event.artist
    artist.set_color(np.random.random(3))
    print "click!"
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)

1 Answer 1

10
import sys
import numpy as np
import matplotlib.pyplot as plt

testData = np.array([[0,0], [0.1, 0], [0, 0.3], [-0.4, 0], [0, -0.5]])
fig, ax = plt.subplots()
coll = ax.scatter(testData[:,0], testData[:,1], color=["blue"]*len(testData), picker = 5, s=[50]*len(testData))
plt.grid(True)
plt.axis([-0.5, 0.5, -0.5, 0.5])

def on_pick(event):
    print testData[event.ind], "clicked"
    coll._facecolors[event.ind,:] = (1, 0, 0, 1)
    coll._edgecolors[event.ind,:] = (1, 0, 0, 1)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to select more than one marker at the same time to retrieve data behind them? Like drawing in rectangle on the scatter plot and do something with all markers inside the rectangle.
user337 there is a lasso functionality: matplotlib.org/3.2.1/gallery/widgets/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.