我需要建立一个网络,其中节点是网站,并且应该根据分配的分数进行分组。如果网站是新网站,则它将带有标签1,否则为0。
数据示例:
url score label
web1 5 1
web2 10 1
web3 5 0
web4 2 0
...
我试图使用networkx来构建网络。要将分数基于Web分组在一起,我只是将score作为一个公共节点(但是可能会有更好的表示方法)。 我想根据标签列为Web着色,但是我不知道该怎么做。 我的代码是:
import networkx as nx
G = nx.from_pandas_edgelist(df, 'url', 'score')
nodes = G.nodes()
plt.figure(figsize=(40,50))
pos = nx.draw(G, with_labels=True,
nodelist=nodes,
node_size=1000)
希望您能给我一些提示。
答案 0 :(得分:1)
如果您也想将score
作为节点包括在内,则分区图可能是一个好主意。您可以像以前一样使用nx.from_pandas_edgelist
创建图,然后将节点属性更新为:
B = nx.from_pandas_edgelist(df, source='url', target='score')
node_view = B.nodes(data=True)
for partition_nodes, partition in zip((df.url, df.score), (0,1)):
for node in partition_nodes.to_numpy():
node_view[node]['bipartite'] = partition
现在,我们具有每个节点的分区属性:
B.nodes(data=True)
NodeDataView({'web1': {'bipartite': 0}, 5: {'bipartite': 1}, 'web2':
{'bipartite': 0}, 10: {'bipartite': 1}, 'web3': {'bipartite': 0},
'web4': {'bipartite': 0}, 2: {'bipartite': 1}})
图形可以用分区布局表示:
part1_nodes = [node for node, attr in B.nodes(data=True) if attr['bipartite']==0]
fig = plt.figure(figsize=(12,8))
plt.box(False)
nx.draw_networkx(
B,
pos = nx.drawing.layout.bipartite_layout(B, part1_nodes),
node_color=[]
node_size=800)