如何给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.
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_labelsusing the edge attributes stored in the graph. label_poscontrols where the label sits on the edge (0.3 places it closer to the source node; adjust based on your preference).- The
bboxparameter adds a white background to labels to make them easier to read against colored edges.
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_labelattribute. - You can switch the layout by changing the
nameparameter in thelayoutdictionary (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

