networkx 的图形简单操作

networkx的简单使用

networkx简介

Python的一个软件包,可以用来研究拓扑结构、各种图,我就知道这么多。想画网络结构图,别人给我推荐了这个工具。

版本号

  • matplotlib 3.0.3
  • networkx 2.3
  • python 3.6.5

这里强调一下,networkx 在绘图时会调用matplotlib,但是matplotlib最新的版本丢弃了原来的一些函数什么的,所以,如果用高于3.0版本以上的matplotlib会出现一些警告或错误。我之前安装的是3.1,会发出警告,所以又重新装了一下matplotlib。可能networkx 更新后会解决这些问题,但是,目前(2019-08-27)没有。
警告如下:
MatplotlibDeprecationWarning:The iterable function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use np.iterable instead. if not cb.iterable(width):

本人遇到过警告,所以找了一下解决方法,这里有个链接个人觉得讲的非常好,出现警告的原因-讲解链接

networkx安装

跟其他python库一样:

pip install networkx

这里再提一下安装指定版本的matplotlib,
先把原来的卸载

pip uninstall matplotlib

再装别的版本,这里我安装的3.0版本的

pip install matplotlib==3.0.*

练习代码

代码都很简单,相信大家一看就懂。里面写了注释。我分成几块内容:

需import的 库

import networkx as nx
import matplotlib.pyplot as plt         # 导入Matplotlib的plot界面,注意导入的文件包,并不是直接导入matplotlib

图的生长

def graph_test01():
    # 图的生长
    g = nx.Graph()
    # 添加节点
    g.add_node(0)                       # 添加一个节点
    g.add_nodes_from([1, 2, 10])        # 添加一个列表节点
    g.add_nodes_from(range(3, 9))       # 添加一列节点,如果是[range(3, 9)],则会添加一个数组作为节点
    # 添加连边
    edge1 = (4, 5)                      # 一条连边
    g.add_edge(*edge1)                  # 添加一条连边,注意要加*,否则报错
    g.add_edge(3, 4)                    # 添加一条连边
    g.add_edges_from([(1, 2), (4, 6)])  # 添加一条多条连边
    nx.draw(g, with_labels=True)        # 绘图,并显示节点序号
    plt.show()                          # 显示
    g.clear()                           # 删除图中的所有连边和节点

结果如图
networkx 的图形简单操作_第1张图片

图的绘制

还有其他绘图时参数,慢慢发掘吧

def graph_test02():
    # 绘制图
    G = nx.petersen_graph()
    plt.subplot(121)
    nx.draw(G, with_labels=True, font_weight='bold')
    plt.subplot(122)
    nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')
    plt.show()

将另一个图的节点或边添加到本图

结果如下
networkx 的图形简单操作_第2张图片

def graph_test03():
    # 用另一个图的数据来生长
    G = nx.Graph()
    H = nx.path_graph(10)       # H是一个链状网络,有10个节点,依次相连
    G.add_nodes_from(H)         # 将H中的节点添加到G中,但是不添加连边
    G2 = nx.Graph()
    G2.add_edges_from(H.edges)  # 将H中的连边添加到图G2中
    plt.subplot(131)
    nx.draw(H, with_labels=True)
    plt.subplot(132)
    nx.draw(G, with_labels=True)
    plt.subplot(133)
    nx.draw(G2, with_labels=True)
    plt.show()

结果如下,从左到右依次是三个图:
networkx 的图形简单操作_第3张图片

添加时会忽略已经存在的节点或边

def graph_test04():
    # 向图添加新的边或节点时会忽略已经存在的节点或边
    G = nx.Graph()
    nodes = range(0, 5)                     # 节点为0,1,2,3,4
    G.add_nodes_from(nodes)                 # 将nodes中的点添加进图G
    G.add_node(2)                           # 2已经在图中,会忽略
    G.add_edges_from([(1, 2), (5, 3)])      # 添加两条边,这里在加边的同时添加了节点5,因为原网络没有节点5
    G.add_edge(1, 2)                        # 1--2连边已经存在,忽略
    G.add_node("happy")                     # 将happy这个整体作为一个节点添加到网络
    G.add_nodes_from("happy")               # 将happy拆分,一个字符作为一个节点,注意有两个p,会忽略掉一个
    G.add_edge(4, 'h')
    nx.draw(G, with_labels=True)
    plt.show()
    nodes_number = G.number_of_nodes()      # 网络中节点个数11
    edges_number = G.number_of_edges()      # 网络中连边个数3
    print('number of nodes: ', nodes_number)
    print('number of edges: ', edges_number)

结果如下:
networkx 的图形简单操作_第4张图片

图形的基本属性

def graph_test05():
    # 图形的基本属性
    G = nx.Graph()
    G.add_nodes_from(range(0, 6))
    G.add_edges_from([(1, 2), (2, 3), (0, 4)])
    nodes = list(G.nodes)                               # 网络中所有的节点
    edges = list(G.edges)                               # 网络中所有的连边
    neighbors = list(G.adj[2])                          # 节点2的所有邻居节点
    degree = G.degree[2]                                # 节点2的度值
    print('nodes:', nodes, '\nedges: ', edges)
    print("neighbors of node 2:", neighbors)
    print("degree of node 2:", degree)

结果如下:
networkx 的图形简单操作_第5张图片

节点和边的移除

def graph_test06():
    # 节点和边的移除
    G = nx.Graph()
    G.add_nodes_from(range(0, 6))
    G.add_nodes_from("hello world")
    edge_list = [(1, 2), (2, 3), (0, 4), (0, 5), ('h', 'e')]
    G.add_edges_from(edge_list)
    plt.subplot(121)
    nx.draw(G, with_labels=True)

    G.remove_node(0)                                # 去除节点0,同时也会去除从节点0出发的连边
    G.remove_nodes_from("world")                    # 去除节点w,o,r,l,d
    G.remove_edge(2, 3)                             # 去除连边2--3
    G.remove_edges_from([(1, 2), ('h', 'e')])       # 去除多条连边
    plt.subplot(122)
    nx.draw(G, with_labels=True)
    plt.show()

结果如下图:左右各是一个图哦,没有画条线将它们分开,( ╯□╰ )
networkx 的图形简单操作_第6张图片

程序入口

我把每一块测试内容单独写成一个函数,所以还有一个主函数~~~
注释掉了不想测试的~~~

def main():
    # graph_test01()
    # graph_test02()
    # graph_test03()
    # graph_test04()
    # graph_test05()
    graph_test06()


if __name__ == '__main__':
    main()

总结

有待探索。

你可能感兴趣的:(python,学习,日常编程遇到的小问题)