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()
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/jacke121/article/details/122783422
内容来源于网络,如有侵权,请联系作者删除!