Null Salad - 1 year ago 85

Python Question

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`

`on_pick`

`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 Source

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

```
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()
```