0

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?

Math
  • 191
  • 2
  • 5
  • 19
  • 1
    Pass `edge_attr=['Age']` to `from_pandas_edgelist`? – Quang Hoang Jan 26 '21 at 20:00
  • thanks a lot, Quang Hoang. Would it be something similar for the node colour? – Math Jan 26 '21 at 20:10
  • unfortunately I cannot see any changes to the edges :( I would like to have different size/weights (with labels whether possible, in order to see if it correctly assigns the length/size/weights) – Math Jan 26 '21 at 20:56

1 Answers1

1

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

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • Hi Scott Boston, I am trying to use this answer adding information on labels: `nx.draw_networkx_labels(G, pos, labels, font_size=16)` but it seems to be wrong. Labels should be from Person1. Could you please let me know if it is better to open a new question for this or if you could let me know here? many thanks – Math Jan 27 '21 at 19:57
  • 1
    Yes.... you have to ensure the order of the nodes take a look at this post (https://stackoverflow.com/a/52683100/6361531). – Scott Boston Jan 27 '21 at 19:59
  • Thanks you so much. It was very useful! – Math Jan 27 '21 at 20:01
  • I have written a new post on an issue that I have had creating a graph. In case you want to have a look at it, please see here: https://stackoverflow.com/questions/66112129/graph-with-nodes-having-size-direction-and-colour-from-pandas-columns thanks a lot – Math Feb 09 '21 at 03:07