6.1 用python代码绘制以下图形
用python绘制一个无向图:v1在中间,v2、v3、v4、v5、v6在周围;v1与v2、v3、v4相连;v2与v3、v6、v1相连;v3与v1、v2、v4相连;v4与v1、v3、v5相连;v5与v4、v6相连;v6与v2、v5相连
点击查看代码
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
G.add_nodes_from(nodes)
edges = [
('v1', 'v2'), ('v1', 'v3'), ('v1', 'v4'),
('v2', 'v3'), ('v2', 'v6'),
('v3', 'v4'),
('v4', 'v5'),
('v5', 'v6')
]
G.add_edges_from(edges)
pos = nx.circular_layout(G)
center = (0, 0)
pos['v1'] = center
plt.figure(figsize=(8, 8))
nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=700, font_size=15, font_weight='bold')
plt.title("Undirected Graph as Described")
plt.axis('equal')
plt.show()
print("学号:3004")
用python绘制一个无向图:v1在中间,v2、v3、v4、v5、v6在周围,要显示权重;v1与v2相连,权重为7;v1与v3相连,权重为3;v1与v4相连,权重为12;v2与v3相连,权重为1;v2与v6相连,权重为1;v3与v4相连,权重为8;v4与v5相连,权重9;v5与v6相连,权重为3
点击查看代码
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
G.add_nodes_from(nodes)
edges = [
('v1', 'v2', 7),
('v1', 'v3', 3),
('v1', 'v4', 12),
('v2', 'v3', 1),
('v2', 'v6', 1),
('v3', 'v4', 8),
('v4', 'v5', 9),
('v5', 'v6', 3)
]
G.add_weighted_edges_from(edges)
pos = nx.circular_layout(G)
center = (0, 0)
pos['v1'] = center
def draw_edges_with_weights(G, pos):
edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.figure(figsize=(10, 10))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=700, font_size=15, font_weight='bold')
draw_edges_with_weights(G, pos)
plt.title("Undirected Graph with Weights")
plt.axis('equal')
plt.show()
print("学号:3004")
用python绘制一个有向图:v1在中间,v2、v3、v4、v5、v6在周围,要显示权重;v2指向v1,权重为7;v1指向v3,权重为3;v4指向v1,权重为12;v2指向v3,权重为1;v6指向v2,权重为1;v3指向v4,权重为8;v5指向v4,权重9;v5指向v6,权重为3
点击查看代码
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
nodes = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
G.add_nodes_from(nodes)
edges = [
('v2', 'v1', 7),
('v1', 'v3', 3),
('v4', 'v1', 12),
('v2', 'v3', 1),
('v6', 'v2', 1),
('v3', 'v4', 8),
('v5', 'v4', 9),
('v5', 'v6', 3)
]
G.add_weighted_edges_from(edges)
pos = nx.circular_layout(G)
def draw_edges_with_weights(G, pos):
edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='red')
plt.figure(figsize=(10, 10))
nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=700, font_size=15, font_weight='bold', arrows=True)
draw_edges_with_weights(G, pos)
plt.title("Directed Graph with Weights")
plt.axis('equal')
plt.show()
print("学号:3004")