import networkx as nx
import matplotlib.pyplot as plt
fig = plt.figure()
# 下两行图上显示中文
mpl.rcParams['font.sans-serif'] = ['SimHei']
node_color = ['r']
data = {'张三':
{'校友': ['李一','李二','李三','李四'],
'同学': ['王一', '王二', '王三', '王四', '王五'],
'同事': ['马一', '马二', '马三', '马四', '马五', '马六']
}
}
G = nx.Graph()
for k, v in data.items():
G.add_node(k, id='0001')
for m, n in v.items():
if m == '校友':
node_color.extend(['b'] * len(n))
for i in n:
G.add_node(i, id='0002')
G.add_edge(k, i, weight=0.1)
elif m == '同学':
node_color.extend(['b'] * len(n))
for i in n:
G.add_node(i, id='0003')
G.add_edge(k, i, weight=0.5)
else:
node_color.extend(['b'] * len(n))
for i in n:
G.add_node(i,id = '0003')
G.add_edge(k,i,weight=1.0)
def on_press(event,relations):
# print(event)
# print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
# (event.button, event.x, event.y, event.xdata, event.ydata))
if event.button == 1:
for k,v in relations.items():
if all([v[0][0] <event.xdata <v[0][1],v[1][0]<event.ydata<v[1][1]]):
print(k)
print(G.node[k]['id'])
pos = nx.spring_layout(G)
po_annotation = []
relations = {}
for po in pos:
print(po, pos[po])
xy = [[pos[po][0] - 0.05, pos[po][0] + 0.05],
[pos[po][1] - 0.05, pos[po][1] + 0.05]]
relations[po] = xy
fig.canvas.mpl_connect('button_press_event',lambda event:on_press(event,relations))
nx.draw(G, pos, with_labels=True,node_color=node_color, edge_color='b', node_size=1000) # ,with_labels=True
plt.show()
网友评论