简体   繁体   中英

how to highlight line collection in matplotlib

I am trying to use mpldatacursor module ( https://stackoverflow.com/users/325565/joe-kington ) to highlight lines in matplotlib. I found examples to highlight lines at https://github.com/joferkington/mpldatacursor . In the example the lines were plotted one-by-one. In my code below, I want to plot the lines using line collection because there are so many lines to plot.

But when I run the code and I click on a line, it does not highlight it. Please, correct what I am doing wrong, many thanks.

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import mpldatacursor

if __name__ == '__main__':
fig, ax = plt.subplots()        
xlist = [[(0.21, 0.50), (0.42, 0.80)], [(0.13, 0.62), (0.46, 0.77), (0.81, 0.90)], [(0.32, 0.12), (0.64, 0.80)], [(0.54, 0.20), (0.87, 0.80)]]

lineCollection = LineCollection(xlist)
lines = ax.lines
mpldatacursor.HighlightingDataCursor(lines)
ax.add_collection(lineCollection)

plt.show()

You can get the index of line in pick_event handler, and change the color:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

fig, ax = plt.subplots()        
xlist = [[(0.21, 0.50), (0.42, 0.80)], [(0.13, 0.62), (0.46, 0.77), (0.81, 0.90)],
         [(0.32, 0.12), (0.64, 0.80)], [(0.54, 0.20), (0.87, 0.80)]]

normal_selected_color = np.array([[0, 0, 1, 1.0], [1, 0, 0, 1.0]])
selected = np.zeros(len(xlist), dtype=int)
colors = normal_selected_color[selected]
lines = LineCollection(xlist, pickradius=10, colors=colors)
lines.set_picker(True)

ax.add_collection(lines)

def on_pick(evt):
    if evt.artist is lines:
        ind = evt.ind[0]
        selected[ind] = 1 - selected[ind]
        lines.set_color(normal_selected_color[selected])
        fig.canvas.draw_idle()


fig.canvas.mpl_connect("pick_event", on_pick)
plt.show()

To select only one line:

def on_pick(evt):
    if evt.artist is lines:
        ind = evt.ind[0]
        selected[:] = 0
        selected[ind] = 1
        lines.set_color(normal_selected_color[selected])
        fig.canvas.draw_idle()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM