代码见下,虽然缩进可能吞掉:
import networkx as nx
import 网页链接 as plt
# 定义关系节点和关系线
relation_node = {
'a': ['b', 'c', 'd', 'e'],
'b': ['a'],
'd': ['c', 'e'],
'e': ['b', 'c'],
}
relation_line = {
'a -> b': '1\n11111\n111\n111',
'a -> c': '2',
'a -> d': 'ad\nabstract',
'a -> e': 'ef',
'b -> a': '3',
'd -> e': '4',
}
# 创建有向图
G = nx.DiGraph()
# 添加节点
for node in relation_node:
G.add_node(node)
# 添加边和边的属性
for edge, attr in relation_line.items():
src, tgt = edge.split(' -> ')
G.add_edge(src, tgt, label=attr)
# 为每个节点设置位置
pos = nx.spring_layout(G)
# 绘制图形
plt.figure(figsize=(8, 6))
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
# 绘制边
for edge in G.edges():
# 如果是双向边,添加弧度偏移
if G.has_edge(edge[1], edge[0]):
nx.draw_networkx_edges(
G, pos, edgelist=[edge],
connectionstyle=f'arc3, rad=0.2', # 添加弧度偏移
arrows=True
)
else:
# 单向边保持直线
nx.draw_networkx_edges(
G, pos, edgelist=[edge],
arrows=True
)
# 绘制边标签
edge_labels = nx.get_edge_attributes(G, 'label')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, rotate=False)
plt.show()
import networkx as nx
import 网页链接 as plt
# 定义关系节点和关系线
relation_node = {
'a': ['b', 'c', 'd', 'e'],
'b': ['a'],
'd': ['c', 'e'],
'e': ['b', 'c'],
}
relation_line = {
'a -> b': '1\n11111\n111\n111',
'a -> c': '2',
'a -> d': 'ad\nabstract',
'a -> e': 'ef',
'b -> a': '3',
'd -> e': '4',
}
# 创建有向图
G = nx.DiGraph()
# 添加节点
for node in relation_node:
G.add_node(node)
# 添加边和边的属性
for edge, attr in relation_line.items():
src, tgt = edge.split(' -> ')
G.add_edge(src, tgt, label=attr)
# 为每个节点设置位置
pos = nx.spring_layout(G)
# 绘制图形
plt.figure(figsize=(8, 6))
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
# 绘制边
for edge in G.edges():
# 如果是双向边,添加弧度偏移
if G.has_edge(edge[1], edge[0]):
nx.draw_networkx_edges(
G, pos, edgelist=[edge],
connectionstyle=f'arc3, rad=0.2', # 添加弧度偏移
arrows=True
)
else:
# 单向边保持直线
nx.draw_networkx_edges(
G, pos, edgelist=[edge],
arrows=True
)
# 绘制边标签
edge_labels = nx.get_edge_attributes(G, 'label')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, rotate=False)
plt.show()