参考博客文章:
这里是引用https://blog.csdn.net/D_Ddd0701/article/details/131057961
名著人物关系
# 使用名著中的人物关系建立图
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv("E:\\download\\三国演义\\triples.csv")
df.head()
# 通过边列表创建有向图
G = nx.DiGraph()
edges = [edge for edge in zip(df['head'], df['tail'])] # 使用zip构建边列表
print(edges)
G.add_edges_from(edges)
G.edges('关羽')
# 可视化
pos = nx.spring_layout(G, seed=123)
plt.figure(figsize=(15,15))
nx.draw(G, pos, with_labels=True)
如图所示
美化图
原始图
seed = 13648
G = nx.random_k_out_graph(10, 3, 0.5, seed=seed)
pos = nx.spring_layout(G, seed=seed)
nx.draw(G, pos, with_labels=True)
如图所示:
美化:
from igraph.drawing.shapes import mpl
# 美化
node_size = [12 + 10*i for i in range(len(G))]
print(node_size)
M = G.number_of_edges() # 边
print(M)
edge_colors = range(2, M+2)
edge_alphas = [(5+i)/ (M+4) for i in range(M)]
cmap = plt.cm.plasma
plt.figure(figsize=(10,8))
nodes = nx.draw_networkx_nodes(G, pos,node_size=node_size, node_color='indigo')
edges = nx.draw_networkx_edges(
G,
pos,
node_size=node_size,
arrowstyle='->',
arrowsize=20,
edge_color=edge_colors,
edge_cmap = cmap,
width=4
)
for i in range(4):
edges[i].set_alpha(edge_alphas[i])
pc = mpl.collections.PathCollection(edges, cmap=cmap)
pc.set_array(edge_colors)
plt.colorbar(pc)
ax = plt.gca()
ax.set_axis_off()
plt.show()
如图所示:
最大连通域子图
这部分是我比较感兴趣的,是怎么找到连通域子图的,
# 最大连通域子图
import networkx as nx
import matplotlib.pyplot as plt
G = nx.gnp_random_graph(100, 0.02, seed=10374196)
pos = nx.spring_layout(G, seed = 10)
nx.draw(G ,pos)
画最大连通子图
'''
先是得到图中的所有连通组件,然后排序取第一个元素就是最大的一个连通图,获取子图
'''
Gcc = G.subgraph(sorted(nx.connected_components(G), key=len,reverse=True)[0])
pos = nx.spring_layout(Gcc, seed=10396953)
nx.draw_networkx_nodes(Gcc, pos, node_size=20)
nx.draw_networkx_edges(Gcc, pos, alpha=0.4)
两幅图如下所示: