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
127 views
in Technique[技术] by (71.8m points)

python - Node size depending on degrees

I am trying to set the node size equal to nodes' degree.

My dataset is

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

My code for building the network is

pos=nx.spring_layout(G, k=0.20, iterations=30)
nx.draw_networkx_nodes(G, pos, node_size = degrees, nodelist=collist['value'], node_color=collist['Wedding'])
nx.draw_networkx_edges(G, pos, width = [I['Age'] for i in dict(G.edges).values()])

I tried to define the degree as follows

degrees=[]
for x in df['Person1']: # all nodes size should depend on the degree, so also for Person2. Maybe this step is wrong 
    deg=G.degree[x]  
    degrees.append(deg)

but it seems to be not a scalar.

The error is

ValueError: s must be a scalar, or the same size as x and y

EDIT: I forgot to give an example of collist['value']:

Wedding variable    value
0   Green   Person1 Adam John
1   Green   Person1 Mary Abbey

... ... ... ...
75  Green   Person2 Yao Ming
76  Green   Person2 Adam Lebron
question from:https://stackoverflow.com/questions/65941163/node-size-depending-on-degrees

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

1 Reply

0 votes
by (71.8m points)

Assuming that nodes in G have been obtained from columns Person1 and Person2, the number of "persons" in df['Person1'] is different from the total number of nodes in G, or at least in nodelist=collist['value'].

An easy fix would be to consider the degree of every node in G. Basically you were right, this step is wrong:

for x in df['Person1']:

you can change it to:

for x in G.nodes():

or use list comprehension:

degrees = [G.degree[node] for node in G.nodes()]

Or if you want only the nodes in collist['value']:

degrees = [G.degree[node] for node in collist['value']]

Small Example:

G = nx.barabasi_albert_graph(100, 2, seed=42)


degrees = [G.degree[node] for node in G.nodes()]

pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size = degrees)
nx.draw_networkx_edges(G, pos, alpha=0.1)

Result:
Result from example above


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

...