709 1

[程序分享] python程序请教 [推广有奖]

  • 0关注
  • 0粉丝

本科生

24%

还不是VIP/贵宾

-

威望
0
论坛币
30794 个
通用积分
0
学术水平
0 点
热心指数
0 点
信用等级
0 点
经验
187 点
帖子
17
精华
0
在线时间
151 小时
注册时间
2020-8-15
最后登录
2024-1-23

楼主
勤劳的飞呀飞 发表于 2020-9-3 12:35:48 |AI写论文
100论坛币
qq.jpg

最佳答案

fengfeng1104 查看完整内容

#%% 基于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') #解决负号'-'显示为方块的问题 ...
关键词:python

沙发
fengfeng1104 发表于 2020-9-3 12:35:49
#%%  基于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')

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-1-7 07:56