我正在尝试使用 mpldatacursor 模块(https://stackoverflow.com/users/325565/joe-kington)突出显示matplotlib中的行。我找到了在https://github.com/joferkington/mpldatacursor处突出显示行的示例。在该示例中,线是逐个绘制的。在下面的代码中,我想使用线条集合绘制线条,因为要绘制的线条太多了。
但是当我运行代码并点击一行时,它不会突出显示它。请纠正我做错了什么,非常感谢。
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()
答案 0 :(得分:1)
您可以在pick_event处理程序中获取行索引,并更改颜色:
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()
只选择一行:
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()