charlopa24
charlopa24

Reputation: 93

Dynamic node sizes in pyvis

I'm wanting to make nodes different sizes depending on the number of connections. However, it seems like this functionality isn't present in pyvis? Maybe I'm missing something or it might not be supported entirely.

Here's my sample code:

import networkx as nx
import matplotlib.pyplot as plt
from pyvis.physics import Physics
from pyvis.network import Network

G = nx.Graph()
G.add_edges_from([(1,2), (2,3), (2,4), (3,4)])

d = dict(G.degree)

print(d.keys())
print([v * 100 for v in d.values()])

nx.draw(G, nodelist=d.keys(), node_size=[v * 100 for v in d.values()])
plt.show()

G2 = Network(height="1500px", width="75%",bgcolor="#222222",font_color="white",directed=True)
G2.from_nx(G)
G2.show("network_map.html")

Upvotes: 0

Views: 6329

Answers (1)

jylls
jylls

Reputation: 4695

You can do that in a few lines by using the set_node_attributes function from networkx. It allows you to add/modify node attributes (see more info here). See below where I used it to change the size of the nodes:

import networkx as nx
import matplotlib.pyplot as plt
from pyvis.physics import Physics
from pyvis.network import Network

G = nx.Graph()

G.add_edges_from([(1,2), (2,3), (2,4), (3,4)])

scale=10 # Scaling the size of the nodes by 10*degree
d = dict(G.degree)

#Updating dict
d.update((x, scale*y) for x, y in d.items())

#Setting up size attribute
nx.set_node_attributes(G,d,'size')

G2 = Network(height="1500px", width="75%",bgcolor="#222222",font_color="white",directed=True)
G2.from_nx(G)
G2.show("network_map.html")

And the output gives:

enter image description here

Upvotes: 4

Related Questions