Skip to content Skip to sidebar Skip to footer

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 f

Solution 1:

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#---------------defon_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

Solution 2:

This wasn't working because I didn't update the plot using plt.show() and used the incorrect getter method. Here's the correct 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#---------------defon_pick(event):

    thisline = event.artist
    thisline.set_markerfacecolor("red")
    plt.show()


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


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

plt.show()

Post a Comment for "Changing Marker Colour On Selection In Matplotlib"