精华内容
下载资源
问答
  • 图分区 使用 Networkx python 库实现不同的分区算法
  • NetWorkx Python API

    2020-05-21 16:50:36
    networkx在2002年5月产生,是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。 networkx支持创建简单无向图、有向图和多重图...

    networkx整理

    1、基础知识

    1.1、介绍

    networkx在2002年5月产生,是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。

    networkx支持创建简单无向图、有向图和多重图;内置许多标准的图论算法,节点可为任意数据;支持任意的边值维度,功能丰富,简单易用。

    1.2、作用

    利用networkx可以以标准化和非标准化的数据格式存储网络、生成多种随机网络和经典网络、分析网络结构、建立网络模型、设计新的网络算法、进行网络绘制等。

    1.3、Graph

    1.3.1、Graph的定义

    Graph是用点和线来刻画离散事物集合中的每对事物间以某种方式相联系的数学模型。

    网络作为图的一个重要领域,包含的概念与定义更多,如有向图网络(Directed Graphs and Networks)、无向图网络(Undirected)等概念。

    Graph在现实世界中随处可见,如交通运输图、旅游图、流程图等。此处我们只考虑由点和线所组成的图。

    利用图可以描述现实生活中的许多事物,如用点可以表示交叉口,点之间的连线表示路径,这样就可以轻而易举的描绘出一个交通运输网络。

    1.3.2、Graph的结构

    根据Graph的定义,一个Graph包含一个节点集合和一个边集。

    在NetworkX中,一个节点可以是任意hash对象(除了None对象),一条边也可以关联任意的对象,像一个文本字符串,一幅图像,一个XML对象,甚至是另一个图或任意定制的节点对象。

    注意:Python中的None对象是不可以作为节点的类型的。

    节点与边能够存储任意类型字典的属性和任意其他丰富类型的数据。

    1.3.3、Graph分类

    • Graph:指无向图(undirected Graph),即忽略了两节点间边的方向。
    • DiGraph:指有向图(directed Graph),即考虑了边的有向性。
    • MultiGraph:指多重无向图,即两个结点之间的边数多于一条,又允许顶点通过同一条边和自己关联。
    • MultiDiGraph:多重图的有向版本。

     

    G = nx.Graph() # 创建无向图
    
    G = nx.DiGraph() # 创建有向图
    
    G = nx.MultiGraph() # 创建多重无向图
    
    G = nx.MultiDigraph() # 创建多重有向图
    
    G.clear() #清空图

     

    2、基本操作

     2.1、无向图

    • 节点 

    ————如果添加的节点和边是已经存在的,是不会报错的,NetworkX会自动忽略掉已经存在的边和节点的添加。

     

    #添加节点
    
    import networkx as nx
    import matplotlib.pyplot as plt
     
    G = nx.Graph()                 #建立一个空的无向图G
    G.add_node('a')                  #添加一个节点1
    G.add_nodes_from(['b','c','d','e'])    #加点集合
    G.add_cycle(['f','g','h','j'])         #加环
    H = nx.path_graph(10)          #返回由10个节点挨个连接的无向图,所以有9条边
    G.add_nodes_from(H)            #创建一个子图H加入G
    G.add_node(H)                  #直接将图作为节点
    
    nx.draw(G, with_labels=True)
    plt.show()

     

    #访问节点
    
    print('图中所有的节点', G.nodes())
    
    print('图中节点的个数', G.number_of_nodes())

     

    #删除节点
    
    G.remove_node(1)    #删除指定节点
    G.remove_nodes_from(['b','c','d','e'])    #删除集合中的节点
    
    nx.draw(G, with_labels=True)
    
    plt.show()

     

     

    #添加边
    
    F = nx.Graph() # 创建无向图
    F.add_edge(11,12)   #一次添加一条边
    
    #等价于
    e=(13,14)        #e是一个元组
    F.add_edge(*e) #这是python中解包裹的过程
    
    F.add_edges_from([(1,2),(1,3)])     #通过添加list来添加多条边
    
    #通过添加任何ebunch来添加边
    F.add_edges_from(H.edges()) #不能写作F.add_edges_from(H)
    
    nx.draw(F, with_labels=True)
    plt.show()

     

    #访问边
    
    print('图中所有的边', F.edges())
    
    print('图中边的个数', F.number_of_edges()) 

     

     

    #快速遍历每一条边,可以使用邻接迭代器实现,对于无向图,每一条边相当于两条有向边
    FG = nx.Graph()
    FG.add_weighted_edges_from([(1,2,0.125), (1,3,0.75), (2,4,1.2), (3,4,0.275)])
    for n, nbrs in FG.adjacency():
        for nbr, eattr in nbrs.items():
            data = eattr['weight']
            print('(%d, %d, %0.3f)' % (n,nbr,data))
    
    print('***********************************')
    
    #筛选weight小于0.5的边:
    FG = nx.Graph()
    FG.add_weighted_edges_from([(1,2,0.125), (1,3,0.75), (2,4,1.2), (3,4,0.275)])
    for n, nbrs in FG.adjacency():
        for nbr, eattr in nbrs.items():
            data = eattr['weight']
            if data < 0.5:
                print('(%d, %d, %0.3f)' % (n,nbr,data))
    print('***********************************')
    
    #一种方便的访问所有边的方法:
    for u,v,d in FG.edges(data = 'weight'):
        print((u,v,d))

     

     

    #删除边
    
    F.remove_edge(1,2)
    F.remove_edges_from([(11,12), (13,14)])
    
    nx.draw(F, with_labels=True)
    
    plt.show()

     

    • 属性

    属性诸如weight,labels,colors,或者任何对象,你都可以附加到图、节点或边上。

    对于每一个图、节点和边都可以在关联的属性字典中保存一个(多个)键-值对。

    默认情况下这些是一个空的字典,但是我们可以增加或者是改变这些属性。

     

    #图的属性
    
    import networkx as nx
    import matplotlib.pyplot as plt
    
    G = nx.Graph(day='Monday')    #可以在创建图时分配图的属性
    print(G.graph)
    
    G.graph['day'] = 'Friday'     #也可以修改已有的属性
    print(G.graph)
    
    G.graph['name'] = 'time'      #可以随时添加新的属性到图中
    print(G.graph)

     

     

    #节点的属性
    
    G = nx.Graph(day='Monday')
    G.add_node(1, index='1th')             #在添加节点时分配节点属性
    print(G.node(data=True))
    
    G.node[1]['index'] = '0th'             #通过G.node[][]来添加或修改属性
    print(G.node(data=True))
    
    G.add_nodes_from([2,3], index='2/3th') #从集合中添加节点时分配属性
    print(G.nodes(data=True))
    
    print(G.node(data=True))

     

     

    #边的属性
    
    G = nx.Graph(day='manday')
    G.add_edge(1,2,weight=10)                    #在添加边时分配属性
    print(G.edges(data=True))
    
    G.add_edges_from([(1,3), (4,5)], len=22)     #从集合中添加边时分配属性
    print(G.edges(data='len'))
    
    G.add_edges_from([(3,4,{'hight':10}),(1,4,{'high':'unknow'})])
    print(G.edges(data=True))
    
    G[1][2]['weight'] = 100000                   #通过G[][][]来添加或修改属性
    print(G.edges(data=True))

     

    注意

    注意什么时候使用‘=’,什么时候使用‘:’;什么时候有引号什么时候没有引号。

    特殊属性weight应该是一个数值型的,并且在算法需要使用weight时保存该数值。

     2.2、其他图

    有向图和多重图的基本操作与无向图一致。

    无向图与有向图之间可以相互转换,转化方法如下:

     

    #有向图转化成无向图
    
    H=DG.to_undirected()
    #或者
    H=nx.Graph(DG)
    
    #无向图转化成有向图
    
    F = H.to_directed()
    #或者
    F = nx.DiGraph(H)

     

    3、Functions

    degree(G[, nbunch, weight]):返回单个节点或nbunch节点的度数视图。 

    degree_histogram(G):返回每个度值的频率列表。

    density(G):返回图的密度。

    info(G[, n]):打印图G或节点n的简短信息摘要。

    create_empty_copy(G[, with_data]):返回图G删除所有的边的拷贝。

    is_directed(G):如果图是有向的,返回true。

    add_star(G_to_add_to, nodes_for_star, **attr):在图形G_to_add_to上添加一个星形。

    add_path(G_to_add_to, nodes_for_path, **attr):在图G_to_add_to中添加一条路径。

    add_cycle(G_to_add_to, nodes_for_cycle, **attr):向图形G_to_add_to添加一个循环。

    • 节点

    nodes(G):在图节点上返回一个迭代器。

    number_of_nodes(G):返回图中节点的数量。

    all_neighbors(graph, node):返回图中节点的所有邻居。

    non_neighbors(graph, node):返回图中没有邻居的节点。

    common_neighbors(G, u, v):返回图中两个节点的公共邻居。

    edges(G[, nbunch]):返回与nbunch中的节点相关的边的视图。

    number_of_edges(G):返回图中边的数目。

    non_edges(graph):返回图中不存在的边。

    •  实例:在networkx中列出特定的节点或边缘

     

    import networkx as nx
    import matplotlib.pyplot as plt
    G = nx.DiGraph()
    G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')])
    G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')])
    G.add_edges_from([('n2', 'n21'), ('n2', 'n22')])
    G.add_edges_from([('n13', 'n131'), ('n22', 'n221')])
    G.add_edges_from([('n131', 'n221'), ('n221', 'n131')])
    G.add_node('n5')
    nx.draw(G, with_labels=True)
    plt.show()

     

    1、使用out_degree函数查找所有带有子项的节点:

    >>> [k for k,v in G.out_degree().iteritems() if v > 0]
    ['n13', 'n', 'n131', 'n1', 'n22', 'n2', 'n221', 'n4']

    2、所有没有孩子的节点:

    >>> [k for k,v in G.out_degree().iteritems() if v == 0]
    ['n12', 'n11', 'n3', 'n41', 'n21', 'n5']

    3、所有孤儿节点,即度数为0的节点:

    >>> [k for k,v in G.degree().iteritems() if v == 0]
    ['n5'] 

    4、超过2个孩子的节点:

    >>> [k for k,v in G.out_degree().iteritems() if v > 2]
    ['n', 'n1']

    4、经典图论算法 

    • 最短路径  

    函数调用: 

    dijkstra_path(G, source, target, weight='weight')             ————求最短路径

    dijkstra_path_length(G, source, target, weight='weight')      ————求最短距离

    示例

     

    import networkx as nx
    import pylab 
    import numpy as np
    #自定义网络
    row=np.array([0,0,0,1,2,3,6])
    col=np.array([1,2,3,4,5,6,7])
    value=np.array([1,2,1,8,1,3,5])
    
    print('生成一个空的有向图')
    G=nx.DiGraph()
    print('为这个网络添加节点...')
    for i in range(0,np.size(col)+1):
        G.add_node(i)
    print('在网络中添加带权中的边...')
    for i in range(np.size(row)):
        G.add_weighted_edges_from([(row[i],col[i],value[i])])
    
    print('给网路设置布局...')
    pos=nx.shell_layout(G)
    print('画出网络图像:')
    nx.draw(G,pos,with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5 )
    pylab.title('Self_Define Net',fontsize=15)
    pylab.show()
    
    
    '''
    Shortest Path with dijkstra_path
    '''
    print('dijkstra方法寻找最短路径:')
    path=nx.dijkstra_path(G, source=0, target=7)
    print('节点0到7的路径:', path)
    print('dijkstra方法寻找最短距离:')
    distance=nx.dijkstra_path_length(G, source=0, target=7)
    print('节点0到7的距离为:', distance) 

     

    •  最小生成树

    定义:一个有 n 个结点的连通图的生成树是原图的极小连通子图,且包含原图中的所有 n 个结点,并且有保持图连通的最少的边。 

     示例:

     

    def prim(G, s):
        dist = {}   # dist记录到节点的最小距离
        parent = {} # parent记录最小生成树的双亲表
        Q = list(G.nodes()) # Q包含所有未被生成树覆盖的节点
        MAXDIST = 9999.99    # MAXDIST表示正无穷,即两节点不邻接
    
        # 初始化数据
        # 所有节点的最小距离设为MAXDIST,父节点设为None
        for v in G.nodes():
            dist[v] = MAXDIST
            parent[v] = None
        # 到开始节点s的距离设为0
        dist[s] = 0
    
        # 不断从Q中取出“最近”的节点加入最小生成树
        # 当Q为空时停止循环,算法结束
        while Q:
            # 取出“最近”的节点u,把u加入最小生成树
            u = Q[0]
            for v in Q:
                if (dist[v] < dist[u]):
                    u = v
            Q.remove(u)
    
            # 更新u的邻接节点的最小距离
            for v in G.adj[u]:
                if (v in Q) and (G[u][v]['weight'] < dist[v]):
                    parent[v] = u
                    dist[v] = G[u][v]['weight']
        # 算法结束,以双亲表的形式返回最小生成树
        return parent

     

     

    import matplotlib.pyplot as plt
    import networkx as nx
    
    g_data = [(1, 2, 1.3), (1, 3, 2.1), (1, 4, 0.9), (1, 5, 0.7), (1, 6, 1.8), (1, 7, 2.0), (1, 8, 1.8), (2, 3, 0.9), (2, 4, 1.8), (2, 5, 1.2), (2, 6, 2.8), (2, 7, 2.3), (2, 8, 1.1), (3, 4, 2.6), (3, 5, 1.7), (3, 6, 2.5), (3, 7, 1.9), (3, 8, 1.0), (4, 5, 0.7), (4, 6, 1.6), (4, 7, 1.5), (4, 8, 0.9), (5, 6, 0.9), (5, 7, 1.1), (5, 8, 0.8), (6, 7, 0.6), (6, 8, 1.0), (7, 8, 0.5)]
    
    def draw(g):
        pos = nx.spring_layout(g)
        nx.draw(g, pos, \
                arrows=True, \
                with_labels=True, \
                nodelist=g.nodes(), \
                style='dashed', \
                edge_color='b', \
                width=2, \
                node_color='y', \
                alpha=0.5)
        plt.show()
    
    g = nx.Graph()

     

     

    tree = prim(g, 1)
    
    mtg = nx.Graph()
    mtg.add_edges_from(tree.items())
    mtg.remove_node(None)
    
    draw(mtg)

     

    • 最大联通子图及联通子图规模排序

     

    import matplotlib.pyplot as plt
    import networkx as nx
    G=nx.path_graph(4)
    G.add_path([10,11,12])
    nx.draw(G,with_labels=True,label_size=1000,node_size=1000,font_size=20)
    plt.show()
    #[print(len(c)) for c in sorted(nx.connected_components(G),key=len,reverse=True)]
    for c in sorted(nx.connected_components(G),key=len,reverse=True):
        print(c)      #看看返回来的是什么?结果是{0,1,2,3}
        print(type(c))   #类型是set
        print(len(c))   #长度分别是4和3(因为reverse=True,降序排列)
     
     
    largest_components=max(nx.connected_components(G),key=len)  # 高效找出最大的联通成分,其实就是sorted里面的No.1
    print(largest_components)  #找出最大联通成分,返回是一个set{0,1,2,3}
    print(len(largest_components))  #4

     

     

    {0, 1, 2, 3}
    <class 'set'>
    4
    {10, 11, 12}
    <class 'set'>
    3
    {0, 1, 2, 3}
    4

     

       

    参考资料:

    http://yoghurt-lee.online/2017/03/30/graph-visible/

    http://blog.sciencenet.cn/home.php?mod=space&uid=404069&do=blog&id=337442

    http://www.cnblogs.com/kaituorensheng/p/5423131.html#_label3

    http://baiyejianxin.iteye.com/blog/1764048

    https://zhuanlan.zhihu.com/p/33616557

    https://blog.csdn.net/qq_31192383/article/details/53748129

    https://blog.csdn.net/newbieMath/article/details/73800374

    http://osask.cn/front/ask/view/565531

    展开全文
  • 系统仿真 首先在ubuntu上你应该为python安装networkx和matplotlib sudo apt-get install python-pip pip install networkx sudo apt-get install python-matplotlib 跑步python gui.py ##例子
  • Python NetworkX module allows us to create, manipulate, and study structure, functions, and dynamics of complex networks. Python NetworkX模块允许我们创建,操纵和研究复杂网络的结构,功能和动态。 1. ...

    Python NetworkX module allows us to create, manipulate, and study structure, functions, and dynamics of complex networks.

    Python NetworkX模块允许我们创建,操纵和研究复杂网络的结构,功能和动态。

    1. Python NetworkX (1. Python NetworkX)

    • NetworkX is suitable for real-world graph problems and is good at handling big data as well.

      NetworkX适用于现实世界中的图形问题,也擅长处理大数据
    • As the library is purely made in python, this fact makes it highly scalable, portable and reasonably efficient at the same time.

      由于该库纯粹是用python制作的,因此这一事实使它同时具有高度的可伸缩性,可移植性和合理的效率。
    • It is open source and released under 3-clause BSD License.

      它是开源的,并根据3条款BSD许可发布。

    2.为什么选择NetworkX? (2. Why NetworkX?)

    NetworkX gives you a lot of reasons to go with it. Following are some features of NetworkX that makes it a package to go with:

    NetworkX为您提供了很多使用它的理由。 以下是NetworkX使其与之配套的一些功能:

    • NetworkX has numerous standard graph algorithms

      NetworkX具有众多标准图形算法
    • It supports data structures for graphs, digraphs, and multigraphs

      它支持图,有向图和多图的数据结构
    • It provides various network structure and measures for analysis

      它提供了各种网络结构和分析措施
    • Making classic/random graphs and synthetic networks is much easier using generators provided in the package

      使用软件包中提供的生成器,制作经典/随机图和合成网络要容易得多
    • Nodes in your network or graph can be absolutely anything, be it images, XML data or anything else

      网络或图形中的节点绝对可以是任何东西,可以是图像,XML数据或其他任何东西
    • Edges also can hold arbitrary data like timestamp and weight

      边缘还可以保存时间戳和权重之类的任意数据
    • It has been well tested with about 90% code coverage

      它已经过良好的测试,大约90%的代码覆盖率

    Apart from above, it has an additional benefit because it is based on pure Python and so, it has a fast-prototyping syntax and very easy to learn. Let’s get started!

    除此之外,它还具有其他优势,因为它基于纯Python,因此,它具有快速原型语法并且非常易于学习。 让我们开始吧!

    3. NetworkX入门 (3. Getting Started with NetworkX)

    NetworkX requires Python >= 2.7 installed on the machine. Let’s complete the installation as a first step.

    NetworkX需要在计算机上安装Python> = 2.7。 首先,让我们完成安装。

    3.1)安装NetworkX模块 (3.1) Install NetworkX Module)

    We can install NetworkX using Python Package Index (pip):

    我们可以使用Python Package Index(pip)安装NetworkX:

    pip install networkx

    In case you face any issues while installing the package using pip, install it from GitHub using the git command:

    如果在使用pip安装软件包时遇到任何问题,请使用git命令从GitHub安装它:

    pip install git://github.com/networkx/networkx.git

    3.2)使用NetworkX (3.2) Using NetworkX)

    Now that we have NetworkX installed on our machine, we can use it in any of our scripts using the following import statement:

    现在我们已经在计算机上安装了NetworkX,我们可以使用以下import语句在任何脚本中使用它:

    import networkx

    3.3)创建图 (3.3) Creating Graphs)

    As NetworkX library is used to manage relationships using the Graph structure, we can get started by creating a graph with no nodes and edges:

    由于NetworkX库用于使用Graph结构管理关系,因此我们可以开始创建一个没有节点和边的图:

    import networkx
    graph = networkx.Graph()

    Since there are no nodes or edges we can’t see the graph so let’s use idle to check if a graph is created or not:

    networkx python graph library

    由于没有节点或边,因此我们看不到图形,因此让我们使用idle检查是否创建了图形:

    3.4)将节点添加到图 (3.4) Adding Nodes to a Graph)

    Adding and checking nodes is quite simple and can be done as:

    添加和检查节点非常简单,可以通过以下方式完成:

    graph.add_node(1)

    Or using list as:

    或将列表用作:

    graph.add_nodes_from([2,3])

    And to see the nodes in existing graph:

    并查看现有图中的节点:

    graph.nodes()

    When we run these set of commands, we will see the following output:

    networkx graph add nodes

    As of now, a graph does exist in the system but the nodes of the graphs aren’t connected. This can be done using the edges in a graph which makes a path between two Graph nodes.

    运行这些命令集时,将看到以下输出:

    到目前为止,系统中确实存在图,但是图的节点尚未连接。 这可以使用图的边缘来完成,该图在两个Graph节点之间建立路径。

    3.5)在节点之间添加边 (3.5) Adding Edges between nodes)

    Adding and checking edges is quite simple as well and can be done as:

    添加和检查边缘也非常简单,可以通过以下方式完成:

    graph.add_edge(1,2)

    Or using list as:

    或将列表用作:

    graph.add_edges_from([(1,2),(2,3)])

    And to see the nodes in existing graph, we can again print the edges of the graph object:

    为了查看现有图形中的节点,我们可以再次打印图形对象的边缘:

    graph.edges()

    When we run these set of commands, we will see the following output:

    networkx graph add edges

    运行这些命令集时,将看到以下输出:

    4.属性 (4. Attributes)

    Graphs are data structures which are used to connect related data and show the relationship between them by using a weight. This weight can be called an attribute of the relation of the two nodes in the Graph. Also, to exhibit properties for a node or an edge or for the graph itself, we can use attributes as well.

    图形是数据结构,用于连接相关数据并通过权重显示它们之间的关系。 该权重可以称为图中两个节点的关系的属性。 同样,要显示节点或边线或图形本身的属性,我们也可以使用属性。

    4.1)图形属性 (4.1) Graph Attributes)

    We can assign meta-data to a Graph by adding graph attributes to a Graph object. Let’s see a code snippet on how this can be done:

    通过将图形属性添加到Graph对象,我们可以将元数据分配给Graph。 让我们看一下如何做到这一点的代码片段:

    graph.graph["day"]="Monday"
    graph.graph

    4.2)节点属性 (4.2) Node Attributes)

    Here, we will add attributes to the nodes of the Graph object:

    在这里,我们将属性添加到Graph对象的节点:

    graph.add_node(1, time='5pm')
    graph.add_nodes_from([3], time='2pm')
    graph.node[1]
    graph.node[1]['room'] = 714
    graph.nodes(data=True)

    4.3)边缘属性 (4.3) Edge Attributes)

    Finally, we will assign some attributes to the edges of the Graph object. To assign edge attributes:

    最后,我们将一些属性分配给Graph对象的边缘。 分配边缘属性:

    graph.add_edge(1, 2, weight=4.7 )
    graph.add_edges_from([(3,4),(4,5)], color='red')
    graph.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})])
    graph[1][2]['weight'] = 4.7
    graph.edge[1][2]['weight'] = 4

    Once we have added the attributes to the Graph, the nodes and the edges, we can finally print all the data:

    networkx graph attributes

    将属性添加到图,节点和边后,我们最终可以打印所有数据:

    5.有向图 (5. Directed Graph)

    In the last section, we saw we could assign attributes to edges of a Graph. We can create a directed graph and add weighted edges as shown below.

    在上一节中,我们看到可以将属性分配给Graph的边缘。 我们可以创建一个有向图并添加加权边,如下所示。

    DG=networkx.DiGraph()
    DG.add_weighted_edges_from([(1,2,0.5), (3,1,0.75)])
    DG.out_degree(1,weight='weight')
    DG.degree(1,weight='weight')
    DG.successors(1)
    DG.neighbors(1)

    Once we run these commands, we will be able to see neighbors and successors of the Graph we just made:

    networkx directed graph

    一旦运行了这些命令,我​​们将能够看到我们刚刚制作的图的邻居和后继者:

    6.绘图图 (6. Drawing Graph)

    So far we have been performing various operations on graphs but not able to visualize any of the operations. Now let’s try to visualize them. For this, we’ll need the help of matplotlib library:

    到目前为止,我们一直在对图形执行各种操作,但无法可视化任何操作。 现在,让我们尝试形象化它们。 为此,我们需要matplotlib库的帮助:

    import matplotlib.pyplot as plt
    networkx.draw(graph)
    networkx.draw_random(graph)
    networkx.draw_circular(graph)
    networkx.draw_spectral(graph)
    plt.show()

    And the result of above-created graphs can be seen as:

    networkx graph plotting

    上面创建的图的结果可以看成是:

    7.结论 (7. Conclusion)

    In this post, we have seen that NetworkX make it very easy to create and work with graphs. We have seen several examples of creating graphs and assigning attributes, weights, and direction to the edges of the Graphs as well.

    在本文中,我们已经看到NetworkX使创建和使用图形变得非常容易。 我们已经看到了几个创建图形并将属性,权重和方向分配给图形边缘的示例。

    NetworkX makes it easy to create graphs without much of hassle and with just a few lines of code. It also has generators for graphs and various networks and also it’s easy to analyze the graphs.

    NetworkX使创建图形变得容易,而没有太多麻烦,只需要几行代码。 它还具有用于图形和各种网络的生成器,并且易于分析图形。

    Reference: API Doc

    参考: API文档

    翻译自: https://www.journaldev.com/19410/networkx-python-graph-library

    展开全文
  • I am having some problems in visualizing the graphs created with python-networkx, I want to able to reduce clutter and regulate the distance between the nodes (I have also tried spring_layout, it just...

    I am having some problems in visualizing the graphs created with python-networkx, I want to able to reduce clutter and regulate the distance between the nodes (I have also tried spring_layout, it just lays out the nodes in an elliptical fashion). Please advise.

    LeJWB.png

    Parts of code:

    nx.draw_networkx_edges(G, pos, edgelist=predges, edge_color='red', arrows=True)

    nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False, style='dashed')

    # label fonts

    nx.draw_networkx_labels(G,pos,font_size=7,font_family='sans-serif')

    nx.draw_networkx_edge_labels(G,pos,q_list,label_pos=0.3)

    解决方案

    In networkx, it's worth checking out the graph drawing algorithms provided by graphviz via nx.graphviz_layout.

    I've had good success with neato but the other possible inputs are

    dot - "hierarchical" or layered drawings of directed graphs. This is the default tool to use if edges have directionality.

    neato - "spring model'' layouts. This is the default tool to use if the graph is not too large (about 100 nodes) and you don't know anything else about it. Neato attempts to minimize a global energy function, which is equivalent to statistical multi-dimensional scaling.

    fdp - "spring model'' layouts similar to those of neato, but does this by reducing forces rather than working with energy.

    sfdp - multiscale version of fdp for the layout of large graphs.

    twopi - radial layouts, after Graham Wills 97. Nodes are placed on concentric circles depending their distance from a given root node.

    circo - circular layout, after Six and Tollis 99, Kauffman and Wiese 02. This is suitable for certain diagrams of multiple cyclic structures, such as certain telecommunications networks.

    In general, graph drawing is a hard problem. If these algorithms are not sufficient, you'll have to write your own or have networkx draw parts individually.

    展开全文
  • networkxPython中的网络分析
  • chapter1快速开始import networkx as nxfrom matplotlib import pyplot as pltG = nx.Graph() # create a graph objectG.add_node('A') # 一次添加一个节点(这里使用字母作为节点的id)G.add_nodes_from(['B','C']) #...

    chapter1

    快速开始

    import networkx as nx

    from matplotlib import pyplot as plt

    G = nx.Graph() # create a graph object

    G.add_node('A') # 一次添加一个节点(这里使用字母作为节点的id)

    G.add_nodes_from(['B','C']) # 添加多个节点

    G.add_edge('A','B') # 一次添加一条边

    G.add_edges_from([('B','C'),('A','C')]) # 一次添加多条

    G.add_edges_from([('B', 'D'), ('C', 'E')])

    plt.figure(figsize=(7.5,7.5)) # 7.5英寸*7.5英寸

    nx.draw_networkx(G)

    plt.show()

    图像的全局配置

    plt.rcParams.update({

    'figure.figsize':(7.5,7.5)

    })

    chapter2

    学习目标

    Graph:了解无向网络的属性以及它们如何使用NetworkX Graph类表示。

    Attributes:如何将数据与节点和边关联。

    Edge Weight:了解如何量化连接强度并为边信息添加注释。

    DiGraph:了解有向网络的属性以及如何使用NetworkX DiGraph类表示。

    MultiGraph and MultiDiGraph:了解拥有并行边的网络。

    Graph类——无向网络

    import networkx as nx

    from matplotlib import pyplot as plt

    G = nx.karate_club_graph()

    karate_pos = nx.spring_layout(G,k = 0.3) # 节点直接通过一条边连接,将会靠的更近

    plt.figure()

    nx.draw_networkx(G,karate_pos)

    plt.show()

    1771072-20200904222213507-122899260.png

    Graph类提供了许多节点和边进行交互的方法:

    获取节点和边的属性的迭代器

    list(G.nodes) # [0,1,2...]

    list(G.edges) # [(0,1),(0,2)...]

    判断节点或边是否存在(根据id匹配)

    hyh = 0

    hyh in G # True

    G.has_node(hyh) #True

    member_id = 1

    (hyh,member_id) in G.edges #True

    G.has_edge(hyh,member_id) #True

    获取节点的邻居,通常,通过一条边连接到某个特定节点的节点集称为该节点的邻居。

    list(G.neighbors(hyh)) #[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31]

    为节点和边添加属性

    有时候,网络节点和边缘被附加了额外的信息。在Graph类中,每个节点和边都可以有一组属性来存储这些附加信息。属性可以简单地作为存储与节点和边相关的信息的方便场所,也可以用于可视化和网络算法。

    Graph类允许您向节点添加任意数量的属性。对于网络G,每个节点的属性都存储在G处的dict中。节点[v],其中v是节点的ID。

    遍历节点,添加club属性

    member_club = [

    0, 0, 0, 0, 0, 0, 0, 0, 1, 1,

    0, 0, 0, 0, 1, 1, 0, 0, 1, 0,

    1, 0, 1, 1, 1, 1, 1, 1, 1, 1,

    1, 1, 1, 1]

    for node_id in G.nodes:

    G.nodes[node_id]["club"] = member_club[node_id]

    G.add_node(11, club=0)

    定制节点的颜色

    node_color = [

    '#1f78b4' if G.nodes[v]["club"] == 0

    else '#33a02c' for v in G]

    nx.draw_networkx(G, karate_pos, label=True, node_color=node_color)

    1771072-20200904222252379-1438089601.png

    遍历边

    # Iterate through all edges

    for v, w in G.edges:

    # Compare `club` property of edge endpoints

    # Set edge `internal` property to True if they match

    if G.nodes[v]["club"] == G.nodes[w]["club"]: # 两个节点直接存在联系

    G.edges[v, w]["internal"] = True

    else:

    G.edges[v, w]["internal"] = False

    internal = [e for e in G.edges if G.edges[e]["internal"]] # 存在联系的数组

    external = [e for e in G.edges if not G.edges[e]["internal"]]

    # Draw nodes and node labels 多个线样式,需要绘制多次

    nx.draw_networkx_nodes(G, karate_pos, node_color=node_color)

    nx.draw_networkx_labels(G, karate_pos)

    # Draw internal edges as solid lines

    nx.draw_networkx_edges(G, karate_pos, edgelist=internal)

    # Draw external edges as dashed lines

    nx.draw_networkx_edges(G, karate_pos, edgelist=external, style="dashed")# 虚线

    1771072-20200904222301977-44416585.png

    为边增加权重

    定义计算边权重的函数

    def tie_strength(G, v, w):

    # Get neighbors of nodes v and w in G

    v_neighbors = set(G.neighbors(v))

    w_neighbors = set(G.neighbors(w))

    # Return size of the set intersection

    return 1 + len(v_neighbors & w_neighbors) # 交集大小

    遍历每条边,计算权重

    for v, w in G.edges:

    G.edges[v, w]["weight"] = tie_strength(G, v, w)

    # Store weights in a list

    edge_weights = [G.edges[v, w]["weight"] for v, w in G.edges]

    将边权值传递给spring_layout(),将强连接的节点推的更近。

    # 将边权值传递给spring_layout(),将强连接节点推得更近

    weighted_pos = nx.spring_layout(G, pos=karate_pos, k=0.3, weight="weight")

    # Draw network with edge color determined by weight

    nx.draw_networkx(

    G, weighted_pos, width=8, node_color=node_color,

    edge_color=edge_weights, edge_vmin=0, edge_vmax=6, edge_cmap=plt.cm.Blues)

    # Draw solid/dashed lines on top of internal/external edges

    nx.draw_networkx_edges(G, weighted_pos, edgelist=internal, edge_color="gray")

    nx.draw_networkx_edges(G, weighted_pos, edgelist=external, edge_color="gray", style="dashed")

    1771072-20200904222313206-662274205.png

    有向图

    这次从gxef中读取数据,类型是directed有向图,每条边都包含source和target。

    <?xml version='1.0' encoding='utf-8'?>

    NetworkX 2.2rc1.dev_20181126202121

    26/11/2018

    读取文件中的数据,画出图形。

    G = nx.read_gexf("data/knecht2008/klas12b-net-1.gexf",node_type=int)

    student_pos = nx.spring_layout(G, k=1.5)

    nx.draw_networkx(G, student_pos, arrowsize=20)

    1771072-20200904222326965-859529817.png

    获取节点邻居,后继,前驱。

    list(G.neighbors(20))

    list(G.successors(20))

    list(G.predecessors(20))

    有向图转化为无向图

    # Create undirected copies of G

    G_either = G.to_undirected() # 默认情况下, 只要存在一个方向,就连接

    G_both = G.to_undirected(reciprocal=True) # 两个方向都存在的时候,才会创建

    # Set up a figure

    plt.figure(figsize=(10,5))

    # Draw G_either on left

    plt.subplot(1, 2, 1)

    nx.draw_networkx(G_either, student_pos)

    # Draw G_both on right

    plt.subplot(1, 2, 2)

    nx.draw_networkx(G_both, student_pos)

    1771072-20200904222334047-572704289.png

    并行边

    例:A点到B点有许多条路

    G = nx.MultiGraph()

    G.add_edges_from([

    ("North Bank", "Kneiphof", {"bridge": "Krämerbrücke"}),

    ("North Bank", "Kneiphof", {"bridge": "Schmiedebrücke"}),

    ("North Bank", "Lomse", {"bridge": "Holzbrücke"}),

    ("Lomse", "Kneiphof", {"bridge": "Dombrücke"}),

    ("South Bank", "Kneiphof", {"bridge": "Grüne Brücke"}),

    ("South Bank", "Kneiphof", {"bridge": "Köttelbrücke"}),

    ("South Bank", "Lomse", {"bridge": "Hohe Brücke"})

    ])

    list(G.edges)[0] # ('North Bank', 'Kneiphof', 0)

    G.edges['North Bank', 'Kneiphof', 0] # {'bridge': 'Krämerbrücke'}

    展开全文
  • 介绍:networkxpython的一个库,它为图的数据结构提供算法、生成器以及画图工具。近日在使用ryu进行最短路径获取,可以通过该库来简化工作量。该库采用函数方式进行调用相应的api,其参数类型通常为图对象。函数...
  • python networkx

    2018-02-09 16:20:22
    利用python中的networkx包对复杂网络进行编程可视化并进行处理
  • Python NetworkX

    2021-09-05 09:59:06
    networkx是一个python包,用于创建、操作和研究复杂网络的结构、动态和功能 使用NetworkX,您可以以标准和非标准数据格式加载和存储网络,生成多种类型的随机和经典网络,分析网络结构,构建网络模型,设计新的网络...
  • 阅读目录无向图有向图加权图经典图论算法计算强连通、弱连通子图条件过滤pred,succNetworkX是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行...
  • python 使用networkx.draw()没反应 出现“D:\Anaconda3\lib\site-packages\networkx\drawing\nx_pylab.py:126: MatplotlibDeprecationWarning: pyplot.hold is deprecated.Future behavior will be consistent with ...
  • 二、Pythonnetworkx模块的使用 1.建立图import networkx as nx G=nx.Graph()#创建空的简单图 G=nx.DiGraph()#创建空的简单有向图 G=nx.MultiGraph()#创建空的多图 G=nx.MultiDiGraph()#创建空的有向多图 2.加点、...
  • import networkx as nximport matplotlib.pyplot as plt# 无向图网络G1 = nx.Graph()G1.add_edge('A', 'B')G1.add_edge('A', 'C')G1.add_edge('A', 'D')G1.add_edge('A', 'E')G1.add_edge('B', 'C')G1.add_edge('B',...
  • NetworkX_python之Tutorial

    2019-03-08 11:15:35
    NetworkX是一个用于创建、操作和研究复杂网络的结构、动态和功能的Python包。 NetworkX provides: 研究社会、生物和基础设施网络的结构和动态的工具; 适用于许多应用程序的标准编程接口和图形实现 快速的发展...
  • NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. Website (including documentation): https://networkx.org ...
  • a)networkx简介:主要用于创造、操作复杂网络,以及学习复杂网络的结构、动力学及其功能。...python图论包networks(最短路,最小生成树带包) 例题如下 如图求下列各节点间最短距离 代码实现 import networkx as nx ...
  • After 3 days of trying to install networkx for python 3.4, I am on the verge of giving up and I've decided to seek for help from some of you people who had some experience with this perhaps.I managed ...
  • 我想为图形上的过程设置动画(最好是在NetworkX中).我已经看过this question.但是,当我运行解决方案中给出的代码时,我只看到最终输出.另外,这不会以某些可用格式保存动画.假设我们有以下图形:import networkx as nxg...
  • 网络
  • obonet:将OBO格式的本体加载到networkx中 阅读Python中的OBO格式的本体。 obonet是 方便使用的 废话 pythonic 现代的 简单且经过测试 轻的 利用 这个Python 3.4+软件包将OBO序列化的本体加载到网络中。 函数...
  • NetworkX 是一个 Python 包,用于创建、操作和研究复杂网络的结构、动力学和功能。 图、有向图和多重图的数据结构。 许多标准的图算法。 网络结构和分析措施。 经典图、随机图和合成网络的生成器。 节点可以是“任何...
  • 1.安装python。以前的安装过程多针对旧的版本,所以安装过程中可安装成最新版本。安装成功的标志是可以在DOS中看到python...下载包直接解压到python的安装路径下(C:\python),有一个networkx的文件夹。在cmd窗口命...
  • k = G.subgraph(res) pl.figure() nx.draw_networkx(k, pos=pos) othersubgraph = G.subgraph(range(6,G.order())) nx.draw_networkx(othersubgraph, pos=pos, node_color = 'b') pl.show() 在G.nodes()调用中具有...
  • I need to process a graphml (XML) file created by a yEd graph in order to get the node and edges attributes of that ... I need to do that using the networkX library. I'm new at Python and I have ne...
  • 目前处理非欧数据最常见的方法还是构建图,而networkx一个专门的构建图数据的工具。方便又好用。 先给链接:https://networkx.github.io/ 官方文档:https://networkx.github.io/documentation/latest/ networkx...
  • I need to process a graphml (XML) file created by a yEd graph in order to get the node and edges attributes of that ... I need to do that using the networkX library. I'm new at Python and I have ne...
  • 最近因为数学建模3天速成Python,然后做了一道网络的题,要画网络图。在网上找了一些,发现都是一些很基础的丑陋红点图,并且关于网络的一些算法也没有讲,于是自己进http://networkx.github.io/学习了一下。以下仅博...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 7,752
精华内容 3,100
关键字:

networkxpython

python 订阅