#%% 基于networkx绘制有向图,并计算出入度
import networkx as nx
from PIL import Image
import matplotlib.pyplot as plt
from networkx.drawing.nx_pydot import to_pydot
from matplotlib.font_manager import *
#定义自定义字体,文件名从1.b查看系统中文字体中来,这是Linux字体路径,windows系统的字体路径自查
myfont = FontProperties(fname='C:/Windows/Fonts/simhei.ttf')
#解决负号'-'显示为方块的问题
matplotlib.rcParams['axes.unicode_minus']=False
nodes = ['1','2','3','4','5']
edges = [('1','2',1),('1','3',1),('1','4',1),('5','1',1),('5','4',1)]
#用于显示图片
def ShowGraphForMat(G):
#使用matplotlib保存图片
pos=nx.shell_layout(G)
nx.draw(G,pos,with_labels=True)
plt.savefig('mat.png')
plt.close()
#将前面两张图显示
plt.subplots(figsize=(12,6))
#载入matplotlib的图片
plt.subplot(1,1,1)
plt.imshow(Image.open('mat.png'))
#plt.axis('off')
#去掉坐标刻度
plt.xticks([])
plt.yticks([])
plt.xticks([])
plt.yticks([])
#显示图片
plt.show()
#%% # 自循环有向图
#清除前面的无向图
G.clear()
#定义有向图
G = nx.DiGraph()
#添加节点和边
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
#显示图片
ShowGraphForMat(G)
outdg = dict(G.out_degree())
indg = dict(G.in_degree())
outdf = pd.DataFrame.from_dict(outdg,orient='index',columns=['出度'])
indf = pd.DataFrame.from_dict(indg,orient='index',columns=['入度'])
df = pd.merge(outdf,indf,left_index=True,right_index=True)
df = df.reset_index().rename(columns = {'index':'节点'})
df.to_csv('result.csv',index=False,encoding='GBK')