import networkx as nx
import matplotlib.pyplot as plt
# 创建一个空图
G = nx.Graph()
# 添加节点
G.add_node("A", type="Person", age=30)
G.add_node("B", type="Person", age=25)
G.add_node("C", type="Company", industry="Tech")
# 添加边
G.add_edge("A", "B", relationship="Friend")
G.add_edge("A", "C", relationship="Employee")
G.add_edge("B", "C", relationship="Employee")
# 打印节点和边
print("Nodes:")
for node, data in G.nodes(data=True):
print(node, data)
print("\nEdges:")
for u, v, data in G.edges(data=True):
print(f"{u} - {v}: {data}")
# 可视化图
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color="lightblue", edge_color="gray", node_size=2000, font_size=15)
labels = nx.get_edge_attributes(G, 'relationship')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()