dsmess
dsmess

Reputation: 67

Networkx pyvis: change color of nodes

I have a dataframe that has source: person 1, target: person 2 and in_rewards_program : binary.

I created a network using the pyvis package"


got_net = Network(notebook=True, height="750px", width="100%")
# got_net = Network(notebook=True, height="750px", width="100%", bgcolor="#222222", font_color="white")


# set the physics layout of the network
got_net.barnes_hut()
got_data = df

sources = got_data['source']
targets = got_data['target']

# create graph using pviz network 
edge_data = zip(sources, targets)

for e in edge_data:
    src = e[0]
    dst = e[1]

    #add nodes and edges to the graph
    got_net.add_node(src, src, title=src)
    got_net.add_node(dst, dst, title=dst)
    got_net.add_edge(src, dst)

neighbor_map = got_net.get_adj_list()

# add neighbor data to node hover data
for node in got_net.nodes:
    node["title"] += "    Neighbors:<br>" + "<br>".join(neighbor_map[node["id"]])
    node["value"] = len(neighbor_map[node["id"]]) # this value attrribute for the node affects node size

got_net.show("test.html")

I want to add the functionality where the nodes are different colors based on the value in in_rewards_program. If the source node has 0 then make the node red and if the source node had 1 then make it blue. I am not sure how to do this.

Upvotes: 3

Views: 15639

Answers (1)

Azim Mazinani
Azim Mazinani

Reputation: 733

There is not much information to know more about your data but based on your code I can assume that you can zip "source" and "target" columns with "in_rewards_program" column and make a conditional statement before adding the nodes so that it will change the node color based on the reward value. According to pyvis documentation, you can pass a color parameter with add_node method:

got_net = Network(notebook=True, height="750px", width="100%")

# set the physics layout of the network
got_net.barnes_hut()

sources = df['source']
targets = df['target']
rewards = df['in_rewards_program']

# create graph using pviz network 
edge_data = zip(sources, targets, rewards)

for src, dst, reward in edge_data:
    #add nodes and edges to the graph
    if reward == 0:
        got_net.add_node(src, src, title=src, color='red')
    if reward == 1:
        got_net.add_node(dst, dst, title=dst, color='blue')

    got_net.add_edge(src, dst)

Upvotes: 10

Related Questions