当前位置:   article > 正文

【python视图2】基于networkx的10个绘图技巧

【python视图2】基于networkx的10个绘图技巧

目录

一、说明

二、简单图操作种种

2.1 简单的无向图

2.2 简单的有向图 

2.3 二维网格grid图 和边数据读写

2.4 环图

2.5 全连接神经网络

2.6  分布直方图-度秩图-连同子图

2.7 随机生成

2.8 渐变颜色化 

2.9 Barabási-Albert 网络

2.10 创建一个 G{n,m} 随机图并计算特征值。


一、说明

        networkx在02年5月产生,是用python语言编写的软件包,便于用户对复杂网络进行创建、操作和学习。利用networkx可以以标准化和非标准化的数据格式存储网络、生成多种随机网络和经典网络、分析网络结构、建立网络模型、设计新的网络算法、进行网络绘制等。 ——百度百科

Gallery — NetworkX 3.1 documentation

二、简单图操作种种

2.1 简单的无向图

无向图和有向图的区别:在生成图的时候已经选定。

  • 效果图:

  • 代码示例 
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. G = nx.Graph()
  4. G.add_edge(1, 2)
  5. G.add_edge(1, 3)
  6. G.add_edge(1, 5)
  7. G.add_edge(2, 3)
  8. G.add_edge(3, 4)
  9. G.add_edge(4, 5)
  10. # explicitly set positions
  11. pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}
  12. options = {
  13. "font_size": 36,
  14. "node_size": 3000,
  15. "node_color": "white",
  16. "edgecolors": "black",
  17. "linewidths": 5,
  18. "width": 5,
  19. }
  20. nx.draw_networkx(G, pos, **options)
  21. # Set margins for the axes so that nodes aren't clipped
  22. ax = plt.gca()
  23. ax.margins(0.20)
  24. plt.axis("off")
  25. plt.show()

2.2 简单的有向图 

效果图:

  1. G = nx.DiGraph([(0, 3), (1, 3), (2, 4), (3, 5), (3, 6), (4, 6), (5, 6)])
  2. # group nodes by column
  3. left_nodes = [0, 1, 2]
  4. middle_nodes = [3, 4]
  5. right_nodes = [5, 6]
  6. # set the position according to column (x-coord)
  7. pos = {n: (0, i) for i, n in enumerate(left_nodes)}
  8. pos.update({n: (1, i + 0.5) for i, n in enumerate(middle_nodes)})
  9. pos.update({n: (2, i + 0.5) for i, n in enumerate(right_nodes)})
  10. nx.draw_networkx(G, pos, **options)
  11. # Set margins for the axes so that nodes aren't clipped
  12. ax = plt.gca()
  13. ax.margins(0.20)
  14. plt.axis("off")
  15. plt.show()

2.3 二维网格grid图 和边数据读写

        重点语句:G = nx.grid_2d_graph(5, 5)

  • 图示意:

  • 代码示例 
  1. import matplotlib.pyplot as plt
  2. import networkx as nx
  3. G = nx.grid_2d_graph(5, 5) # 5x5 grid
  4. # print the adjacency list
  5. for line in nx.generate_adjlist(G):
  6. print(line)
  7. # write edgelist to grid.edgelist
  8. nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
  9. # read edgelist from grid.edgelist
  10. H = nx.read_edgelist(path="grid.edgelist", delimiter=":")
  11. pos = nx.spring_layout(H, seed=200)
  12. nx.draw(H, pos)
  13. plt.show()

2.4 环图

用户指定环的位置后画出:

代码

  1. import matplotlib.pyplot as plt
  2. import networkx as nx
  3. import numpy as np
  4. G = nx.path_graph(20) # An example graph
  5. center_node = 5 # Or any other node to be in the center
  6. edge_nodes = set(G) - {center_node}
  7. # Ensures the nodes around the circle are evenly distributed
  8. pos = nx.circular_layout(G.subgraph(edge_nodes))
  9. pos[center_node] = np.array([0, 0]) # manually specify node position
  10. nx.draw(G, pos, with_labels=True)
  11. plt.show()

2.5 全连接神经网络

示例图

示例代码 

  1. import itertools
  2. import matplotlib.pyplot as plt
  3. import networkx as nx
  4. subset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]
  5. subset_color = [
  6. "gold",
  7. "violet",
  8. "violet",
  9. "violet",
  10. "violet",
  11. "limegreen",
  12. "limegreen",
  13. "darkorange",
  14. ]
  15. def multilayered_graph(*subset_sizes):
  16. extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))
  17. layers = [range(start, end) for start, end in extents]
  18. G = nx.Graph()
  19. for i, layer in enumerate(layers):
  20. G.add_nodes_from(layer, layer=i)
  21. for layer1, layer2 in nx.utils.pairwise(layers):
  22. G.add_edges_from(itertools.product(layer1, layer2))
  23. return G
  24. G = multilayered_graph(*subset_sizes)
  25. color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
  26. pos = nx.multipartite_layout(G, subset_key="layer")
  27. plt.figure(figsize=(8, 8))
  28. nx.draw(G, pos, node_color=color, with_labels=False)
  29. plt.axis("equal")
  30. plt.show()

2.6  分布直方图-度秩图-连同子图

        此示例展示了使用两种常用技术可视化节点度分布的几种方法:度秩图和度直方图。

在此示例中,生成了一个包含 100 个节点的随机图。确定每个节点的度数,并生成一个显示三件事的图形:1. 连通分量的子图 2. 图的度秩图,以及 3. 度直方图

  1. import networkx as nx
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. G = nx.gnp_random_graph(100, 0.02, seed=10374196)
  5. degree_sequence = sorted((d for n, d in G.degree()), reverse=True)
  6. dmax = max(degree_sequence)
  7. fig = plt.figure("Degree of a random graph", figsize=(8, 8))
  8. # Create a gridspec for adding subplots of different sizes
  9. axgrid = fig.add_gridspec(5, 4)
  10. ax0 = fig.add_subplot(axgrid[0:3, :])
  11. Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
  12. pos = nx.spring_layout(Gcc, seed=10396953)
  13. nx.draw_networkx_nodes(Gcc, pos, ax=ax0, node_size=20)
  14. nx.draw_networkx_edges(Gcc, pos, ax=ax0, alpha=0.4)
  15. ax0.set_title("Connected components of G")
  16. ax0.set_axis_off()
  17. ax1 = fig.add_subplot(axgrid[3:, :2])
  18. ax1.plot(degree_sequence, "b-", marker="o")
  19. ax1.set_title("Degree Rank Plot")
  20. ax1.set_ylabel("Degree")
  21. ax1.set_xlabel("Rank")
  22. ax2 = fig.add_subplot(axgrid[3:, 2:])
  23. ax2.bar(*np.unique(degree_sequence, return_counts=True))
  24. ax2.set_title("Degree histogram")
  25. ax2.set_xlabel("Degree")
  26. ax2.set_ylabel("# of Nodes")
  27. fig.tight_layout()
  28. plt.show()

2.7 随机生成

  1. import matplotlib as mpl
  2. import matplotlib.pyplot as plt
  3. import networkx as nx
  4. seed = 13648 # Seed random number generators for reproducibility
  5. G = nx.random_k_out_graph(10, 3, 0.5, seed=seed)
  6. pos = nx.spring_layout(G, seed=seed)
  7. node_sizes = [3 + 10 * i for i in range(len(G))]
  8. M = G.number_of_edges()
  9. edge_colors = range(2, M + 2)
  10. edge_alphas = [(5 + i) / (M + 4) for i in range(M)]
  11. cmap = plt.cm.plasma
  12. nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color="indigo")
  13. edges = nx.draw_networkx_edges(
  14. G,
  15. pos,
  16. node_size=node_sizes,
  17. arrowstyle="->",
  18. arrowsize=10,
  19. edge_color=edge_colors,
  20. edge_cmap=cmap,
  21. width=2,
  22. )
  23. # set alpha value for each edge
  24. for i in range(M):
  25. edges[i].set_alpha(edge_alphas[i])
  26. pc = mpl.collections.PatchCollection(edges, cmap=cmap)
  27. pc.set_array(edge_colors)
  28. ax = plt.gca()
  29. ax.set_axis_off()
  30. plt.colorbar(pc, ax=ax)
  31. plt.show()

2.8 渐变颜色化 

 颜色渐变的边

 代码

  1. import matplotlib.pyplot as plt
  2. import networkx as nx
  3. G = nx.star_graph(20)
  4. pos = nx.spring_layout(G, seed=63) # Seed layout for reproducibility
  5. colors = range(20)
  6. options = {
  7. "node_color": "#A0CBE2",
  8. "edge_color": colors,
  9. "width": 4,
  10. "edge_cmap": plt.cm.Blues,
  11. "with_labels": False,
  12. }
  13. nx.draw(G, pos, **options)
  14. plt.show()

 颜色渐变的节点

  1. import matplotlib.pyplot as plt
  2. import networkx as nx
  3. G = nx.cycle_graph(24)
  4. pos = nx.spring_layout(G, iterations=200)
  5. nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues)
  6. plt.show()

2.9 Barabási-Albert 网络

        使用 NetworkX ego_graph() 函数返回 Barabási-Albert 网络中最大枢纽的主要 egonet 的示例。

  1. from operator import itemgetter
  2. import matplotlib.pyplot as plt
  3. import networkx as nx
  4. # Create a BA model graph - use seed for reproducibility
  5. n = 1000
  6. m = 2
  7. seed = 20532
  8. G = nx.barabasi_albert_graph(n, m, seed=seed)
  9. # find node with largest degree
  10. node_and_degree = G.degree()
  11. (largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
  12. # Create ego graph of main hub
  13. hub_ego = nx.ego_graph(G, largest_hub)
  14. # Draw graph
  15. pos = nx.spring_layout(hub_ego, seed=seed) # Seed layout for reproducibility
  16. nx.draw(hub_ego, pos, node_color="b", node_size=50, with_labels=False)
  17. # Draw ego as large and red
  18. options = {"node_size": 300, "node_color": "r"}
  19. nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], **options)
  20. plt.show()

2.10 创建一个 G{n,m} 随机图并计算特征值。

  1. import matplotlib.pyplot as plt
  2. import networkx as nx
  3. import numpy.linalg
  4. n = 1000 # 1000 nodes
  5. m = 5000 # 5000 edges
  6. G = nx.gnm_random_graph(n, m, seed=5040) # Seed for reproducibility
  7. L = nx.normalized_laplacian_matrix(G)
  8. e = numpy.linalg.eigvals(L.toarray())
  9. print("Largest eigenvalue:", max(e))
  10. print("Smallest eigenvalue:", min(e))
  11. plt.hist(e, bins=100) # histogram with 100 bins
  12. plt.xlim(0, 2) # eigenvalues between 0 and 2
  13. plt.show()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/487712
推荐阅读
相关标签
  

闽ICP备14008679号