Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/65908318/customise-settings-for-edges-and-nodes-using-info-from-a-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IIUC:

df = pd.read_clipboard(sep='ss+')

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...