简体   繁体   中英

Networkx node labels are in wrong order

I have a written a code in Python that draws graphs. The input looks like this:

  1. Number of vertices.
  2. 1st coordinate of a vertex.
  3. 2nd coordinate of the same vertex vertex.
  4. Repeat (2) and (3) if there are multiple vertices. Each number must be on a newline.

The graph is drawn correctly, but the labels on each node are wrong.

Example Input:

10
1
3
3
4
1
2
4
2
3
2
2
6
2
5
6
7
5
8
7
8
4

Please enter the input on a newline for each number!!!

Example output:

Correct output

My output(wrong one):

wrong output(the current one)

My code:

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
#f=open("output.txt","r+")
G=nx.Graph()

#ed=input("How many edges?")
ver=int(input("How many vertices?"))


for z in range(0, ver):
    x = int(input())
    y = int(input())
    G.add_edge(x,y)

labelmap = dict(zip(G.nodes(), ["1", "2", "3", "4","5","6","7","8"]))
nx.draw(G, labels=labelmap, with_labels=True)
plt.show()
#, labels=labelmap, with_labels=True

Nodes are added automatically by networkx the first time they are referenced. If you draw an edge from C->B then F->A the nodes will be created in that order (C, B, F, A). However your labelmap is assuming they are in numerical order.

The node labels will be printed correctly on the nodes if you just use:

nx.draw(G, with_labels=True)

Or you can track the nodes as you add them to store the order, eg

nodes = []
for z in range(0, ver):
    x = int(input())
    y = int(input())
    G.add_edge(x,y)

    if x not in nodes:
        nodes.append(x)
    if y not in nodes:
        nodes.append(y)

labelmap = dict(zip(nodes, nodes))

Using this approach you could also format/change the label if you wish.

As I said in comments labels in networkx are assigned automatically:

import networkx as nx
from string import ascii_uppercase

G = nx.Graph()

edges = list(zip(ascii_uppercase, ascii_uppercase[1:]))
print(edges)

for i, j in edges:
    G.add_edge(i, j)

# jupyter notebook
%matplotlib inline
nx.draw(G, with_labels=True)

Output:

[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I'), ('I', 'J'), ('J', 'K'), ('K', 'L'), ('L', 'M'), ('M', 'N'), ('N', 'O'), ('O', 'P'), ('P', 'Q'), ('Q', 'R'), ('R', 'S'), ('S', 'T'), ('T', 'U'), ('U', 'V'), ('V', 'W'), ('W', 'X'), ('X', 'Y'), ('Y', 'Z')]

图形

By default nodes/vertices in networkx have integers as labels:

G = nx.path_graph(15)
print(G.edges())

%matplotlib inline
nx.draw(G, with_labels=True)

Output:

[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12), (12, 13), (13, 14)]

图形

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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