Math
Math

Reputation: 251

Customise settings for edges and nodes using info from a dataframe

Currently I have built a network using NetworkX from source-target dataframe:

import networkx as nx

G = nx.from_pandas_edgelist(df, source='Person1', target='Person2')

Dataset

    Person1            Age       Person2         Wedding
0   Adam John          3        Yao Ming         Green
1   Mary Abbey         5       Adam Lebron       Green
2   Samuel Bradley     24      Mary Lane         Orange
3   Lucas Barney       12      Julie Lime        Yellow
4   Christopher Rice   0.9     Matt Red          Green

I would like to set the size/weights of the links based on the Age column (i.e. age of marriage) and the colour of nodes as in the column Wedding. I know that, if I wanted add an edge, I could set it as follows: G.add_edge(Person1,Person2, size = 10); for applying different colours to nodes I should probably use the parameter node_color=color_map, where color_map should be the list of colours in the Wedding column (if I am right).

Can you please explain me how to apply these settings to my case?

Upvotes: 0

Views: 209

Answers (1)

Scott Boston
Scott Boston

Reputation: 153570

IIUC:

df = pd.read_clipboard(sep='\s\s+')

collist = df.drop('Age', axis=1).melt('Wedding')
collist

G = nx.from_pandas_edgelist(df, source='Person1', target='Person2', edge_attr='Age')

pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, nodelist=collist['value'], node_color=collist['Wedding'])
nx.draw_networkx_edges(G, pos, width = [i['Age'] for i in dict(G.edges).values()])

Output: enter image description here

Upvotes: 1

Related Questions