【问题标题】:Networkx pyvis: change color of nodesNetworkx pyvis:更改节点的颜色
【发布时间】:2020-06-11 02:10:41
【问题描述】:

我有一个数据框,其中包含 source: person 1、target: person 2 和 in_rewards_program: binary。

我使用 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")

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

【问题讨论】:

    标签: html pandas networkx


    【解决方案1】:

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

    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)
    
    

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 2023-03-12
      • 2020-12-22
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      相关资源
      最近更新 更多