在下面的图片中,您可以看到有时连接线太短而无法安装标签,或者连接线相交。我能做些什么?尝试用k的价值或规模弄乱,但似乎没有帮助
不幸的是,NetworkX没有图形布局函数(我知道),它使您可以在连接的长度上放置约束。另外,Spring_layout(这是您选择的内容,而NetworkX默认值)对于断开的图表往往表现不佳;如果允许算法继续进行太多迭代,则连接的组件将慢慢推开。
我认为在这里最有用的方法是在单独的子图中绘制两个连接的组件。我还发现将标签位置移回边缘中心很有用。
这里有一些执行此操作的代码
df = pd.DataFrame({
"part_a": [1, 2, 2, 4, 2, 2, 9, 9, 6, 7, 8, 8, 8, 8, 10],
"part_b": [2, 3, 5, 5, 9, 10, 11, 14, 7, 8, 13, 12, 15, 16, 9],
"type_of_connection": ["snap-fit",
"snap-fit",
"screw",
"screw",
"snap-fit",
"screw",
"clip",
"snap-fit",
"screw",
"screw",
"screw",
"snap-fit",
"screw",
"other",
"screw"]})
G = nx.Graph()
# add nodes
nodes = set(df["part_a"]).union(set(df["part_b"]))
G.add_nodes_from(nodes)
# add edges
for _, row in df.iterrows():
G.add_edge(row["part_a"], row["part_b"], type=row["type_of_connection"])
components = list(nx.connected_components(G))
n = len(components)
all_edge_labels = {(row["part_a"], row["part_b"]): row["type_of_connection"] for _, row in df.iterrows()}
# draw
plt.figure(figsize=(10, 6))
for i, component in enumerate(components, 1):
H = nx.induced_subgraph(G, component)
pos = nx.spring_layout(H, k=0.1, scale=2)
edge_labels = {(a, b): conn_type for (a,b), conn_type in all_edge_labels.items() if a in component}
plt.subplot(1, n, i)
nx.draw(H, pos, with_labels=True, node_size=700, node_color="lightblue", edge_color="gray", alpha=0.8)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=9, label_pos=0.5)
plt.show()
不能保证在边缘标签重叠上完全删除节点,但是我发现1-3尝试后,我似乎最终得到了“幸运”的布局,并删除了重叠。这是一个例子