You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中创建带多条连接线的散点图并自动识别节点间的同值关联

Automatically Connect Nodes by Shared Values in Python (NetworkX)

Great start with your existing NetworkX code! You’ve already nailed the visualization part with curved edges—now let’s solve the core problem: automatically identifying and adding edges between nodes that share the same value (instead of hardcoding each edge manually).

Step 1: Structure Your Data

First, let’s assume your table data is structured like a pandas DataFrame (this is standard for tabular datasets, but we can adapt if you’re using a different format). Here’s a sample that matches your original node positions and adds a "shared value" column (e.g., a group ID that defines which nodes should connect):

import pandas as pd

# Simulate your tabular data
data = pd.DataFrame({
    "node_id": [0, 1, 2, 3, 4, 5, 6],
    "pos_x": [0, 1, 3, 5, 6, 7, 9],
    "shared_value": ["A", "A", "B", "C", "B", "B", "C"]  # Nodes with same value get connected
})

Step 2: Automatically Generate Edges from Shared Values

We’ll group nodes by their shared_value, then create edges between nodes in the same group. You can adjust the edge logic based on your exact needs:

Option 1: Connect a Central Node to All Others in the Group

This matches your original example (where node 2 connects to 4 and 5). We’ll pick the first node in each group as the central node and link it to every other node in the group:

import networkx as nx
import matplotlib.pyplot as plt

# Initialize the directed graph
G = nx.DiGraph()
G.add_nodes_from(data["node_id"])

# Auto-add edges based on shared values
for group, group_nodes in data.groupby("shared_value"):
    node_list = group_nodes["node_id"].tolist()
    if len(node_list) > 1:
        central_node = node_list[0]
        # Link central node to all other nodes in the group
        for node in node_list[1:]:
            G.add_edge(central_node, node)

# Set node positions (pull directly from your data)
pos = {row["node_id"]: [row["pos_x"], 0] for _, row in data.iterrows()}

# Draw the graph with your original styling
nx.draw(
    G,
    pos=pos,
    connectionstyle="arc3,rad=-0.7",
    edge_color="blue",
    node_size=600,
    node_color="#a8e6cf",
    with_labels=True
)
plt.ylim([-0.5, 0.5])
plt.show()

Option 2: Connect All Pairs of Nodes in the Group

If you want every node in the same group to connect to every other node (e.g., node 0 ↔ 1, node 2 ↔ 4, node 2 ↔5, node4 ↔5), use itertools.combinations to generate all pairwise edges:

from itertools import combinations

# Reset the graph for this example
G = nx.DiGraph()
G.add_nodes_from(data["node_id"])

for group, group_nodes in data.groupby("shared_value"):
    node_list = group_nodes["node_id"].tolist()
    if len(node_list) > 1:
        # Generate all unique pairs of nodes in the group
        for u, v in combinations(node_list, 2):
            G.add_edge(u, v)
            # Uncomment below if you want bidirectional edges
            # G.add_edge(v, u)

# Reuse the same position and drawing code as above
nx.draw(
    G,
    pos=pos,
    connectionstyle="arc3,rad=-0.7",
    edge_color="blue",
    node_size=600,
    node_color="#a8e6cf",
    with_labels=True
)
plt.ylim([-0.5, 0.5])
plt.show()

Key Notes

  • If your nodes have unique y-axis positions (not all 0), just add a pos_y column to your DataFrame and update the pos dictionary to [row["pos_x"], row["pos_y"]].
  • Adjust connectionstyle (e.g., rad=0.7 for upward arcs) or edge colors to match your target visualization.
  • If you’re not using pandas, you can group your nodes using a dictionary (map each shared value to a list of node IDs) and follow the same edge-generation logic.

内容的提问来源于stack exchange,提问作者researchcollege111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 16:29:08