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

如何给NetworkX有向图添加CSV边标签并转为Dash交互式图

Hey there! Let's break down how to solve your two tasks: adding edge labels from your CSV's Edge_label column to your NetworkX directed graph, and turning this static visualization into an interactive one with Dash.

1. Adding Edge Labels to Your NetworkX Directed Graph

Your current code loads the edges but doesn't include the Edge_label data. Here's how to fix that:

First, update the from_pandas_edgelist call to include the edge attribute so NetworkX stores the labels:

g = nx.from_pandas_edgelist(
    df, 
    'Source', 
    'Target', 
    edge_attr='Edge_label',  # This loads the Edge_label column as an edge attribute
    create_using=nx.DiGraph()
)

Next, the nx.draw() function doesn't render edge labels directly. You'll need to use nx.draw_networkx_edge_labels() separately. Important: use the same position layout for both the graph drawing and the label placement to avoid misalignment.

Here's the full modified code:

import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx

df = pd.read_csv('Trail_data.csv')
g = nx.from_pandas_edgelist(
    df, 
    'Source', 
    'Target', 
    edge_attr='Edge_label',
    create_using=nx.DiGraph()
)

plt.figure(figsize=(40, 40))
# Define the position first and reuse it
pos = nx.random_layout(g, iterations=20)

# Draw the graph
nx.draw(
    g, 
    pos=pos,
    with_labels=True, 
    node_size=3000,
    node_color='#82CAFF',
    font_size=16, 
    font_weight='bold', 
    font_color='black', 
    edge_color=('#E55451','#810541','#00FF00'), 
    node_shape='o', 
    width=4, 
    arrows=True,
    connectionstyle='arc3, rad=0.11'
)

# Add edge labels
edge_labels = {(u, v): d['Edge_label'] for u, v, d in g.edges(data=True)}
nx.draw_networkx_edge_labels(
    g, 
    pos=pos,
    edge_labels=edge_labels,
    font_size=14,  # Adjust label size as needed
    font_weight='bold',
    label_pos=0.3,  # Position label along the edge (0=source, 1=target)
    bbox=dict(facecolor='white', edgecolor='none', alpha=0.7)  # Optional: add background to labels
)

plt.savefig('Visualization.jpeg', dpi=100)
plt.show()

Key notes here:

  • We extract the edge labels into a dictionary edge_labels using the edge attributes stored in the graph.
  • label_pos controls where the label sits on the edge (0.3 places it closer to the source node; adjust based on your preference).
  • The bbox parameter adds a white background to labels to make them easier to read against colored edges.
2. Creating an Interactive Dash Visualization

For an interactive version, dash-cytoscape is a great tool—it plays nicely with NetworkX and supports built-in interactions like zoom, pan, and node/edge selection.

First, install the required packages:

pip install dash dash-cytoscape pandas networkx

Here's a complete Dash app that converts your NetworkX graph into an interactive visualization:

import pandas as pd
import networkx as nx
import dash
from dash import html, dcc
import dash_cytoscape as cyto

# Load data and create NetworkX graph
df = pd.read_csv('Trail_data.csv')
g = nx.from_pandas_edgelist(
    df, 
    'Source', 
    'Target', 
    edge_attr='Edge_label',
    create_using=nx.DiGraph()
)

# Convert NetworkX graph to Cytoscape format
cyto_data = nx.readwrite.json_graph.cytoscape_data(g)
elements = cyto_data['elements']

# Define styles for nodes and edges
stylesheet = [
    {
        'selector': 'node',
        'style': {
            'background-color': '#82CAFF',
            'label': 'data(id)',
            'font-size': '16px',
            'font-weight': 'bold',
            'width': '60px',
            'height': '60px'
        }
    },
    {
        'selector': 'edge',
        'style': {
            'line-color': '#E55451',
            'width': 4,
            'target-arrow-color': '#E55451',
            'target-arrow-shape': 'triangle',
            'curve-style': 'bezier',
            'control-point-distance': 40,  # Mimics your arc3 connection style
            'label': 'data(Edge_label)',  # Show the edge label
            'font-size': '14px',
            'font-weight': 'bold',
            'text-background-color': 'white',
            'text-background-opacity': 0.7
        }
    }
]

# Initialize Dash app
app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1("Interactive Trail Network Visualization"),
    cyto.Cytoscape(
        id='cytoscape-graph',
        elements=elements,
        stylesheet=stylesheet,
        layout={
            'name': 'random',  # You can use other layouts like 'circle' or 'dagre'
            'iterations': 20
        },
        style={'width': '100%', 'height': '800px'}
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

Key features of this app:

  • Interactive zoom, pan, and drag: Users can manipulate the view to explore the graph.
  • Edge labels are displayed directly on the edges using the Edge_label attribute.
  • You can switch the layout by changing the name parameter in the layout dictionary (try 'dagre' for a directed graph layout).
  • The stylesheet lets you customize node/edge appearance to match your original visualization.

To run the app, save the code to a file (e.g., app.py) and run it with python app.py. You'll see the interactive graph in your browser at http://127.0.0.1:8050/.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:52:58