import networkx as nx import matplotlib.pyplot as plt # 创建图 G = nx.Graph()
时间: 2023-12-09 15:05:49 浏览: 27
# 添加节点
G.add_node(1)
G.add_node(2)
G.add_node(3)
# 添加边
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
# 绘制图形
nx.draw(G, with_labels=True)
plt.show()
相关问题
import networkx as nx import matplotlib.pyplot as plt # create graph object G = nx.Graph() # add nodes G.add_node('A') G.add_node('B') G.add_node('C') G.add_node('D') # add edges with weights G.add_edge('A', 'B', weight=5) G.add_edge('A', 'C', weight=7) G.add_edge('B', 'D', weight=6) G.add_edge('C', 'D', weight=3) # define node positions (optional) pos = {'A': (0, 0), 'B': (1, 1), 'C': (-1, 1), 'D': (0, 2)} # draw nodes and edges with labels nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) plt.axis('off') plt.show()
这段代码也可以用来绘制带权图,它和我之前给出的示例代码有些不同。以下是这段代码的解释:
```python
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_edge('A', 'B', weight=5)
G.add_edge('A', 'C', weight=7)
G.add_edge('B', 'D', weight=6)
G.add_edge('C', 'D', weight=3)
# 定义节点位置
pos = {'A': (0, 0), 'B': (1, 1), 'C': (-1, 1), 'D': (0, 2)}
# 绘制节点和边以及标签
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
# 获取边的权重并绘制标签
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.axis('off')
plt.show()
```
在这个示例中,我们首先创建了一个带权图,然后添加了节点和带权边。接下来,我们定义了节点位置,这是可选的,如果不定义位置,则networkx会自动为节点排列位置。然后我们使用`nx.draw_networkx_nodes`、`nx.draw_networkx_edges`和`nx.draw_networkx_labels`这三个函数来绘制节点和边,并使用`nx.get_edge_attributes`获取边的权重。最后,我们使用`nx.draw_networkx_edge_labels`函数来绘制边的标签。
import networkx as nximport matplotlib.pyplot as plt# 读取人物关系数据with open('characters.txt', 'r') as f: data = f.readlines()# 创建空的Graph对象G = nx.Graph()# 添加节点和边for line in data: characters = line.strip().split(',') for i in range(len(characters)): if not G.has_node(characters[i]): G.add_node(characters[i]) for j in range(i+1, len(characters)): if not G.has_node(characters[j]): G.add_node(characters[j]) if not G.has_edge(characters[i], characters[j]): G.add_edge(characters[i], characters[j])# 绘制图形pos = nx.spring_layout(G)nx.draw(G, pos, with_labels=True, font_size=10, node_size=500, node_color='lightblue', edge_color='gray')plt.show()
这是Python中导入networkx和matplotlib.pyplot模块的语句。networkx是一个用于创建、操作和研究复杂网络的Python库,而matplotlib.pyplot是一个用于绘制图形的Python库。