Networkx pyvis:更改节点的颜色

dsm*_*ess 3 html networkx pandas

我有一个数据框,其中包含source:人员 1、:target人员 2 和in_rewards_program:二进制。

我使用 pyvis 包创建了一个网络”


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")
Run Code Online (Sandbox Code Playgroud)

我想添加以下功能:节点根据 中的值具有不同的颜色in_rewards_program。如果源节点有 0,则将该节点设为红色;如果源节点有 1,则将其设为蓝色。我不知道该怎么做。

小智 10

没有太多信息可以了解有关您的数据的更多信息,但根据您的代码,我可以假设您可以使用“in_rewards_program”列压缩“源”和“目标”列,并在添加节点之前做出条件语句,以便它会改变基于奖励值的节点颜色。根据pyvis 文档color,您可以使用 add_node 方法传递参数:

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)

Run Code Online (Sandbox Code Playgroud)