python复杂网络 学习笔记
【摘要】
networkx库
pip install --upgrade networkx
点和边示例:
import networkx as nximport matplotlib.pyplot as pltG = nx.Graph() #初始化一个图G.add_node('a')G.add_node('b')G.add_n...
networkx库
pip install --upgrade networkx
点和边示例:
-
import networkx as nx
-
import matplotlib.pyplot as plt
-
G = nx.Graph() #初始化一个图
-
G.add_node('a')
-
G.add_node('b')
-
G.add_node('c')
-
G.add_node('d')
-
G.add_node('e')
-
G.add_edge('a','b') #连接a、b得到ab边
-
G.add_edge('a','d')
-
G.add_edge('a','e')
-
G.add_edge('a','c')
-
nx.draw(G,with_labels=True)
-
plt.show()
规则图:
-
import networkx as nx
-
-
import matplotlib.pyplot as plt
-
-
RG = nx.random_graphs.random_regular_graph(3,20) #生成包含20个节点、每个节点有3个邻居的规则图RG
-
-
pos = nx.spectral_layout(RG) #定义一个布局,此处采用了spectral布局方式,后变还会介绍其它布局方式,注意图形上的区别
-
-
nx.draw(RG,pos,with_labels=False,node_size = 30) #绘制规则图的图形,with_labels决定节点是非带标签(编号),node_size是节点的直径
-
-
plt.show() #显示图形
无向图示例:
-
import networkx as nx
-
-
import matplotlib.pyplot as plt
-
-
# BA scale-free degree network
-
-
# generalize BA network which has 20 nodes, m = 1
-
-
BA = nx.random_graphs.barabasi_albert_graph(20, 1)
-
-
# spring layout
-
-
pos = nx.spring_layout(BA)
-
-
nx.draw(BA, pos, with_labels = False, node_size = 30)
-
-
plt.show()
-
# 导入相关依赖
-
from matplotlib import pyplot as plt
-
import networkx as nx
-
import numpy as np
-
-
# 生成随机数据
-
G = nx.erdos_renyi_graph(50,0.5)
-
-
# 指定画布大小
-
plt.figure(figsize=(18,18))
-
-
# 生成新的图
-
G_new = nx.Graph()
-
-
# 依据图中边的数量,生成同样长度的随机权重值
-
weightList = {}
-
for i in range(len(G.edges())+1):
-
weightList[i] = np.random.rand()
-
-
# 将生成的随机权重复制给G_new图
-
i = 0
-
for edge in G.edges():
-
i += 1
-
G_new.add_edges_from([(edge[0], edge[1], {'weight': weightList[i]})])
-
# 绘制G_new图
-
nx.draw_networkx(G_new)
-
plt.show()
文章来源: blog.csdn.net,作者:AI视觉网奇,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/jacke121/article/details/122783422
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)