Assassin
Assassin

Reputation: 72

Networkx: how to add edge labels from csv file in a graph

How can I add Edge label from csv/excel file to networkx directed graph

I want to add labels to my networkx graph from column Edge_label present in csv file

csv_file

import pandas as pd

import matplotlib.pyplot as plt
#%matplotlib inline

import networkx as nx

df = pd.read_csv('Trail_data.csv')

g = nx.from_pandas_edgelist(df,
                            'Source',
                            'Target',
                             create_using=nx.DiGraph() # For Directed Route arrows
                           ) 

plt.figure( figsize=(40, 40)
          )

nx.draw(g,
        with_labels=True,
        node_size= 3000,#k=200,
        node_color='#82CAFF',##00b4d9
        font_size=16,
        font_weight ='bold',
        font_color='black',
        edge_color = ('#E55451','#810541','#00FF00'),
        node_shape='o',
        width=4 ,
        arrows=True, #Show arrow From and To
        pos=nx.random_layout(g),iterations=20,
        connectionstyle='arc3, rad =0.11' #To avoid overlapping edgs
        
       )

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

** Also I wanted to convert this directed graph to interactive graph with python-dash **

Upvotes: 2

Views: 2418

Answers (1)

Sparky05
Sparky05

Reputation: 4892

According to the documentation of from_pandas_edgelist you can simply specify a list of columns with edge_attr.

In your case, you get the desired graph with:

g = nx.from_pandas_edgelist(df,
                            'Source',
                            'Target',
                             edge_attr=`Edge_label`,
                             create_using=nx.DiGraph(),) 

For drawing you currently only draw node labels. You can add edge labels with draw_networkx_edge_labels

pos = nx.random_layout(g)
nx.draw(g, 
        pos=pos, ...)  # add other parameters
edge_labels = nx.get_edge_attributes(g, "Edge_label")
nx.draw_networkx_edge_labels(g, pos, edge_labels)

Upvotes: 1

Related Questions