python – 创建网络图
发布时间:2021-01-17 03:09:57  所属栏目:Python  来源:互联网 
            导读:我以CSV格式设置的样本数据如下. 无向图具有90个节点,以数字{10,11,12 …. 99} 其边缘与权重的定义如下. [样本数据] node1 node2 weight23 89 34.9 (i.e. there is an edge between node 23 and 89 with weight 34.9)75 14 28.5so on.... 我
                
                
                
            | 
                         我以CSV格式设置的样本数据如下. 无向图具有90个节点,以数字{10,11,12 …. 99} [样本数据] node1 node2 weight 23 89 34.9 (i.e. there is an edge between node 23 and 89 with weight 34.9) 75 14 28.5 so on.... 我想以网络形式表示.代表它的有效方法是什么(例如Gephi,networkx等).边缘厚度应代表边缘重量. 解决方法如果你在Linux,并且假设你的csv文件看起来像这样(例如):23;89;3.49 23;14;1.29 75;14;2.85 14;75;2.9 75;23;0.9 23;27;4.9 您可以使用此程序: import os
def build_G(csv_file):
    #init graph dict
    g={}
    #here we open csv file
    with open(csv_file,'r') as f:
        cont=f.read()
    #here we get field content
    for line in cont.split('n'):
        if line != '':
            fields=line.split(';')
            #build origin node
            if g.has_key(fields[0])==False:
                g[fields[0]]={}
            #build destination node         
            if g.has_key(fields[1])==False:
                g[fields[1]]={}
            #build edge origin>destination
            if g[fields[0]].has_key(fields[1])==False:
                g[fields[0]][fields[1]]=float(fields[2])
    return g
def main():
    #filename
    csv_file="mynode.csv"
    #build graph
    G=build_G(csv_file)
    #G is now a python dict
    #G={'27': {},'75': {'14': 2.85,'23': 0.9},'89': {},'14': {'75': 2.9},'23': {'27': 4.9,'89': 3.49,'14': 1.29}}
    #write to file
    f = open('dotgraph.txt','w')
    f.writelines('digraph G {nnode [width=.3,height=.3,shape=octagon,style=filled,color=skyblue];noverlap="false";nrankdir="LR";n')
    f.writelines
    for i in G:
        for j in G[i]:
            #get weight
            weight = G[i][j]
            s= '      '+ i
            s +=  ' -> ' +  j + ' [dir=none,label="' + str(G[i][j]) + '",penwidth='+str(weight)+',color=black]'
            if s!='      '+ i:
                s+=';n'
                f.writelines(s)
    f.writelines('}')
    f.close()
    #generate graph image from graph text file
    os.system("dot -Tjpg -omyImage.jpg dotgraph.txt")
main() 
 我以前正在寻找一个有效的解决方案来构建复杂的图形,这是最简单的(没有任何python模块依赖)方法我发现. 以下是无向图的图像结果(使用dir = none): (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
