** Я могу реагировать на события мыши, когда нажимаю на узлы, поэтому цвет узла меняется. Теперь я хочу сделать то же самое для нажатия на края или метки. Есть идеи, как это сделать?
Вот мой код: **
import pylab as plt
import networkx as nx
from matplotlib.collections import PathCollection
from matplotlib.patches import FancyArrowPatch
from matplotlib.collections import LineCollection
G = nx.DiGraph()
nodes = {'1': [55, 10], '2': [56, 11], '3': [57, 12], '4': [58, 12]}
edges = [('1', '2'), ('3', '4'), ('1', '3')]
G.add_nodes_from(nodes)
G.add_edges_from(edges)
fig, ax = plt.subplots()
pos = nodes
edgelist=edges
nodes = nx.draw_networkx_nodes(G, pos, node_color='blue', node_size=200, alpha=0.8,
edgecolors='black')
nodes.set_picker(5)
edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, edge_color='red', alpha=.4)
# edges.set_picker(10)
labels = nx.draw_networkx_labels(G, pos, font_size=6, font_color='black')
# labels.set_picker(5)
def onpick(event):
if isinstance(event.artist, LineCollection):
all_labels = event.artist
print(all_labels)
ind = event.ind[0] # event.ind is a single element array.
print("ind: ", ind)
this_edge_label = list(edges)[ind]
print("Edgelabel: ", this_edge_label)
colors = [(0, 0, 0.9)] * len(edges)
colors[ind] = (0, 0.9, 0)
all_labels.set_facecolors(colors)
elif isinstance(event.artist, PathCollection):
all_nodes = event.artist
print(all_nodes)
ind = event.ind[0] # event.ind is a single element array.
print("ind: ", ind)
this_node_name = list(pos)[ind]
print("Nodename: ", this_node_name)
# Set the colours for all the nodes, highlighting the picked node with
# a different colour:
colors = [(0, 0, 0.9)] * len(pos)
colors[ind] = (0, 0.9, 0)
all_nodes.set_facecolors(colors)
# Update the plot to show the change:
fig.canvas.draw() # plt.draw() also works.
fig = plt.gcf()
# Bind our onpick() function to pick events:
fig.canvas.mpl_connect('pick_event', onpick)
# Hide the axes:
plt.gca().set_axis_off()
plt.show()