简体   繁体   English

NetworkX:节点标签是随机绘制的

[英]NetworkX: Node labels are drawn randomly

So I wanted to draw labels for each of my node (1-20), but somehow these labels are just drawn randomly on the graph (check screen below). 因此,我想为每个节点(1-20)绘制标签,但是不知何故,这些标签只是在图形上随机绘制的(请参见下面的检查屏幕)。

network = nx.DiGraph()
counter = 0
for i in range(1,21):
    network.add_node(i, label = str(i))
with open('mreza.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=';', quotechar='|')
    for row in reader:
        for item in row:
            item = item.strip('(').strip(')').split(',')
            startVertex = int(item[0])
            endVertex = int(item[1])
            network.add_weighted_edges_from([(startVertex, endVertex, matchingArray[counter])])
            counter = counter + 1
pos=nx.spring_layout(network)
nx.draw(network)
labels = nx.draw_networkx_labels(network,pos,font_size=10)
plt.show()

nan

There are a few issues in your code: 您的代码中存在一些问题:

  • You create nodes and edges separately. 您分别创建节点和边。 The labels that you think are random are associated with nodes that you have created in the first loop (I guess). 您认为是随机的标签与您在第一个循环中创建的节点相关联(我想)。
  • draw can be called with extra argument to draw labels, ie nx.draw(G, pos=pos, with_labels=True, font_size=10) . draw可以用额外的参数来调用绘制的标签,即nx.draw(G, pos=pos, with_labels=True, font_size=10)
  • add_weighted_edges_from is supposed to be given a container of edges. 应该给add_weighted_edges_from一个边的容器。 You're sort of abusing this function to add edges. 您正在滥用此功能来添加边。 If you insist on going with a loop, consider using add_edge . 如果您坚持使用循环,请考虑使用add_edge

Considering that you load your data from csv, I'd not go into loops at all. 考虑到您是从csv加载数据的,所以我根本不会陷入循环。 Instead, I'd load my data into pandas dataframe and then use from_pandas_edgelist like this: 相反,我将数据加载到pandas数据框中 ,然后使用from_pandas_edgelist像这样:

import pandas as pd
import networkx as nx

df = pd.read_csv('mreza.csv')
G = nx.from_pandas_edgelist(df, create_using=nx.DiGraph)
pos = nx.spring_layout(G)
nx.set_node_attributes(G, pos, 'pos')

Mind that your df needs to have two mandatory columns: source and target . 请注意,您的df需要具有两个必填列: sourcetarget Pre-process your df if necessary. 如有必要,请对df预处理。 Add weight and you're done. 增加weight ,您就完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM