Can anyone help how to change the color of a set of points in a pyplot when i click on its legend labels?
Below is a code where there are two set of points x1 and x2. I am plotting them as a scatter plot. It plots all the points in set x1 and x2 in blue color. Is there any way to change the color of the points in set x1 to red when I click on the legend x1 label
import matplotlib.pyplot as plot
x1 = [1,3,5,7,9]
x2 = [2,4,6,8,10]
fig, ax = plot.subplots()
ax.scatter(x1,x1,color = 'b',s = 50,label = 'x1')
ax.scatter(x2,x2,color = 'b',s = 50,label = 'x2')
ax.legend(loc = 'upper left')
plot.show()
There is an example in the matplotlib docs about legend picking . We may adapt it to the case where picking happens on a scatter and the color is to change.
To this end we create a picker on the legend artist (proxy) and attach an attribute toggled
to is to know in which of the two states the artist is in (this is easier than using get_color
due to the colors being converted to RGB tuples internally).
import matplotlib.pyplot as plt
x1 = [1,3,5,7,9]
x2 = [2,4,6,8,10]
fig, ax = plt.subplots()
line1 = ax.scatter(x1,x1,color = 'b',s = 50,label = 'x1')
line2 = ax.scatter(x2,x2,color = 'b',s = 50,label = 'x2')
leg = ax.legend(loc = 'upper left')
# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.legendHandles, lines):
legline.set_picker(5) # 5 pts tolerance
legline.toggled = False # create custom attribute to observe state
lined[legline] = origline
def onpick(event):
legline = event.artist
origline = lined[legline]
c = "b" if legline.toggled else "r"
legline.set_color(c)
origline.set_color(c)
fig.canvas.draw_idle()
legline.toggled = not legline.toggled
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.