首先升级一下networkx到最新版本,命令是:
pip install networkx --upgrade
然后执行下面的代码即可:
#%% 加权有向图
import networkx as nx
import matplotlib.pyplot as plt
df = pd.DataFrame(data ={'from':['李山','李山','王林','张三'],'to':['王林','王林','赵明','李四'],'weights':[3,2,5,2]})
g = nx.from_pandas_edgelist(df,'from','to',['weights'], create_using=nx.MultiDiGraph())
pos = nx.spring_layout(g)
nodes = list(g.nodes)
nlabels = dict(zip(nodes, nodes))
# nx.draw(g, with_labels=True,edge_color=df['weights'],node_size=1500, alpha=0.3, arrows=True,font_family ='YouYuan')
# nx.draw(g,pos,with_labels=True,connectionstyle='arc3, rad = 0.2',width=[float(v['weights']) for (r,c,v) in g.edges(data=True)],node_size=1500, alpha=0.3, arrows=True,font_family ='YouYuan')
nx.draw_networkx_nodes(g, pos, node_color = 'r', node_size = 1500, alpha = 1)
ax = plt.gca()
for e in g.edges(data=True):
ax.annotate("",
xy=pos[e[0]], xycoords='data',
xytext=pos[e[1]], textcoords='data',
arrowprops=dict( color="0.5",width=int(e[2]['weights']),
shrinkA=10, shrinkB=10,mutation_scale=30,
patchA=None, patchB=None,
connectionstyle="arc3,rad=rrr".replace('rrr',str(0.3*e[2]['weights'])
),
),
)
nx.draw_networkx_labels(G, pos, nlabels,font_size=15, font_color='k', font_family='YouYuan', font_weight='normal', alpha=1.0, bbox=None, ax=None) # 标签
plt.axis('off')
plt.show()
dg = pd.DataFrame.from_dict(dict(g.degree(weight='weights')),orient='index',columns=['度'])
indg = pd.DataFrame.from_dict(dict(g.in_degree(weight='weights')),orient='index',columns=['入度'])
outdg =pd.DataFrame.from_dict( dict(g.out_degree(weight='weights')),orient='index',columns=['出度'])
dgdf = pd.merge(pd.merge(dg,indg,left_index=True,right_index=True),outdg,left_index=True,right_index=True)
dgdf = dgdf.reset_index().rename(columns = {'index':'节点'})
dgdf.to_csv('weighted_result.csv',index=False,encoding='GBK')
ps:有问题可留言沟通