Null Salad Null Salad - 6 months ago 35
Python Question

Changing marker colour on selection in matplotlib

I'm using matplotlib and I am trying to change the colour of a marker when it is selected. So far I am plotting the markers and adding a

pick_event
listener that calls an
on_pick
function, which then modifies the plot's marker properties. This isn't working because I can't figure out how to access the marker's properties. How do I do this?

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

#-----------------------------------------------
# Plots several points with cubic interpolation
#-----------------------------------------------
fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(0, 10, num=6, endpoint=True)
y = abs(x**2)

xnew = np.linspace(0, 10, num=40, endpoint=True)
cubicInterp = interp1d(x, y, kind='cubic')
line, = ax.plot(x,y, 'o', picker=5) # 5 points tolerance
lineInterp = ax.plot(xnew,cubicInterp(xnew), '-')

#---------------
# Events
#---------------

def on_pick(event):

line.color='red'
thisline.color='red'


#-----------------------------


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

plt.show()

Answer

You can use setp method to manipulate the plot elements and update the cavas. This works:

Code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

#-----------------------------------------------
# Plots several points with cubic interpolation
#-----------------------------------------------
fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(0, 10, num=6, endpoint=True)
y = abs(x**2)

xnew = np.linspace(0, 10, num=40, endpoint=True)
cubicInterp = interp1d(x, y, kind='cubic')
line = ax.plot(x,y, 'o', picker=5)  # 5 points tolerance
lineInterp = ax.plot(xnew,cubicInterp(xnew), '-')

#---------------
# Events
#---------------

def on_pick(event):
    print "clicked"
    plt.setp(line,'color','red')
    fig.canvas.draw()

#-----------------------------


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

plt.show()

Ouput:

Before: enter image description here

After: enter image description here