公众号:尤而小屋 编辑:Peter 作者:Peter
大家好,我是Peter~
本文给大家带来Networkx绘图的进阶方法,包含:
官网学习地址:https://networkx.org/documentation/stable/auto_examples/drawing/index.html
看下部分效果:
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
import networkx as nx
G = nx.star_graph(20) # 创建星星图;参数表示中心点的邻居数量
pos = nx.spring_layout(G, seed=63) # 布局设置
colors = range(20) # 颜色设置
options = { # 绘图选项
"node_color": "#A01BE2", # 点的颜色
"edge_color": colors, # 边缘色
"width": 3, # 宽线条度
"edge_cmap": plt.cm.Blues,
"with_labels": True, # 是否显示数值
}
nx.draw_networkx(G, pos, **options)
plt.show()
G = nx.path_graph(20) # 20个节点
center_node = 5 # 中心节点
edge_nodes = set(G) - {center_node} # 边缘节点
pos = nx.circular_layout(G.subgraph(edge_nodes)) # 边缘节点布局
pos[center_node] = np.array([0, 0]) # 设置中心节点位置
nx.draw_networkx(G, pos, with_labels=True) # 绘制图形
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cycle_graph(30)
pos = nx.circular_layout(G)
nx.draw_networkx(G, pos, node_color=range(30), node_size=600, cmap=plt.cm.Blues)
plt.show()
# 创建名为"Davis Southern Women"的社交网络图。这个图描述了美国南部一群妇女之间的社交关系。
G = nx.davis_southern_women_graph()
# 社区检测: 使用贪婪模块度最大化算法来检测图中的社区
communities = nx.community.greedy_modularity_communities(G)
# supergraph = nx.cycle_graph(len(communities))
superpos = nx.spring_layout(G, scale=50, seed=429) # 计算原始图的布局
# 初始化节点位置
centers = list(superpos.values())
pos = {}
# 为每个社区计算布局并更新节点位置
for center, comm in zip(centers, communities):
pos.update(nx.spring_layout(nx.subgraph(G, comm), center=center, seed=1430))
# 绘制图的节点和边
for nodes, clr in zip(communities, ("tab:blue", "tab:orange", "tab:green")):
nx.draw_networkx_nodes(G, pos=pos, nodelist=nodes, node_color=clr, node_size=100)
nx.draw_networkx_edges(G, pos=pos)
# tight_layout来自动调整子图和装饰元素的位置;show函数显示图形
plt.tight_layout()
plt.show()
绘制带有权重的图形:
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
# 添加多个边和权重
G.add_edge("a", "b", weight=0.6)
G.add_edge("a", "c", weight=0.2)
G.add_edge("c", "d", weight=0.5)
G.add_edge("c", "e", weight=0.7)
G.add_edge("c", "f", weight=0.9)
G.add_edge("a", "d", weight=0.3)
# 根据阈值0.5选择不同的边
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]
pos = nx.spring_layout(G,seed=7)
# 添加节点
nx.draw_networkx_nodes(G, pos, node_size=700)
# 添加边
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=4) # 权重较大的边
nx.draw_networkx_edges(G, pos, edgelist=esmall, width=4, alpha=0.5, edge_color="b", style="dashed") # 权重较小的边
# 节点labels
nx.draw_networkx_labels(G, pos, font_size=15, font_family="sans-serif")
# edge with labels
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels)
ax = plt.gca()
ax.margins(0.08)
plt.axis("off")
plt.tight_layout()
plt.show()
通过度的秩图和直方图来显示
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
# 创建随机图
G = nx.gnp_random_graph(100, 0.02, seed=1234)
# 获取度序列并排序
degree_sequence = sorted((d for n, d in G.degree()), reverse=True)
d_max = max(degree_sequence)
# 创建图形和网格
fig = plt.figure("Degree of a random graph",figsize=(8,8))
axgrid = fig.add_gridspec(5,4)
# 绘制连通分量
ax0 = fig.add_subplot(axgrid[0:3,:])
Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
pos = nx.spring_layout(Gcc, seed=1234)
nx.draw_networkx_nodes(Gcc, pos, ax=ax0, node_size=20)
nx.draw_networkx_edges(Gcc, pos, ax=ax0, alpha=0.4)
ax0.set_title("Connected components of G")
ax0.set_axis_off()
# 绘制度序列排名图
ax1 = fig.add_subplot(axgrid[3:, :2])
ax1.plot(degree_sequence, "b-", marker="o")
ax1.set_title("Degree Rank Plot")
ax1.set_ylabel("Degree")
ax1.set_xlabel("Rank")
# 绘制度直方图
ax2 = fig.add_subplot(axgrid[3:, 2:])
ax2.bar(*np.unique(degree_sequence, return_counts=True))
ax2.set_title("Degree histogram")
ax2.set_xlabel("Degree")
ax2.set_ylabel("# of Nodes")
fig.tight_layout()
plt.show()
自我网络(Ego graph)是一种特殊类型的网络,由一个中心节点和所有直接与之相连的其他节点组成。
自我网络图(Ego Network Graph)是一种社会网络分析方法,用于研究个体(称为“自我”或“Ego”)及其直接联系人(称为“Alters”)之间的关系。在自我网络图中,一个节点代表自我,其他节点代表与自我有直接联系的人(也被称之为分身),边则表示这些联系。自我网络图有助于了解个体在社会结构中的位置和作用,以及个体如何通过其社交网络影响和受到他人影响。
from operator import itemgetter
import matplotlib.pyplot as plt
import networkx as nx
# 设置Barabási-Albert网络的参数。
# m表示每次添加新节点时,新节点连接到的已存在节点的数量;n-网络中总节点数;seed是随机种子
m, n, seed = 3, 1000, 20532
G = nx.barabasi_albert_graph(n, m, seed=seed)
# 找到度数最大的节点
node_and_degree = G.degree()
(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
# 提取ego网络
hub_ego = nx.ego_graph(G, largest_hub)
# 设置ego网络的布局
pos = nx.spring_layout(hub_ego, seed=seed)
# 绘制网络
nx.draw_networkx(hub_ego, pos, node_color="b", node_size=50, with_labels=False)
# 突出显示度数最大的节点
options = {"node_size": 400, "node_color": "r"}
nx.draw_networkx_nodes(hub_ego,
pos,
nodelist=[largest_hub], **options
)
plt.show()
随机几何图(Random Geometric Graph, RGG)是一种图模型,用于模拟无线通信网络中的节点分布和连接。在随机几何图中,节点是根据一定的几何过程(通常是泊松点过程)随机分布在空间中的,而图中的边则对应于这些节点之间的无线连接。
随机几何图的特性:
import matplotlib.pyplot as plt
import networkx as nx
# 200个节点的随机几何图,连接概率阈值为0.125(如果两个节点之间的距离小于这个值,它们之间存在一个边)
G = nx.random_geometric_graph(200,0.125,seed=1234)
pos = nx.get_node_attributes(G, "pos") # 获取节点位置
dmin = 1 # 当前找到的最小距离
n_center = 0 # 距离最小的节点
for n in pos: # 遍历所有节点;找到距离(0.5,0.5)最近的节点
x,y = pos[n]
d = (x - 0.5) ** 2 + (y - 0.5) ** 2
if d < dmin:
n_center = n
dmin = d
# 计算最短路径长度
p = dict(nx.single_source_shortest_path_length(G, n_center))
plt.figure(figsize=(8,8)) # 图像大小
nx.draw_networkx_edges(G, pos, alpha=0.4) # 绘制边和节点
nx.draw_networkx_nodes(
G,
pos,
nodelist=list(p.keys()), # 节点、大小、颜色、
node_size=80,
node_color=list(p.values()),
cmap=plt.cm.Reds_r, # 色彩映射
)
plt.xlim(-0.05, 1.05) # x-y轴范围
plt.ylim(-0.05, 1.05)
plt.axis("off") # 关闭边框轴
plt.show()
import itertools # 迭代和组合
import matplotlib.pyplot as plt
import networkx as nx
# 子图大小和颜色
subset_sizes = [1, 5, 4, 3, 2, 4, 4, 3]
subset_color = ["gold","violet","violet","violet","violet","limegreen","limegreen","darkorange"]
def multilayered_graph(*subset_sizes):
extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes)) # 计算每层的开始和结束索引
layers = [range(start, end) for start, end in extents]
G = nx.Graph() # 创建图
for i, layer in enumerate(layers): # 遍历层;并添加
G.add_nodes_from(layer, layer=i)
for layer1, layer2 in nx.utils.pairwise(layers): # 保证每一层的每个节点都和下层的每个节点相连
G.add_edges_from(itertools.product(layer1, layer2)) # itertools.product 生成笛卡尔积
return G
G = multilayered_graph(*subset_sizes)
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
# 使用nx.multipartite_layout函数为图中的节点计算位置
pos = nx.multipartite_layout(G, subset_key="layer")
plt.figure(figsize=(6, 6))
nx.draw_networkx(G, pos, node_color=color, with_labels=True) # with_labels 显示数据
plt.axis("equal")
plt.show()
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。