Reputation: 47
I have a written a code in Python that draws graphs. The input looks like this:
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:
My output(wrong 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
Upvotes: 0
Views: 1785
Reputation: 17794
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)
[('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)
[(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)]
Upvotes: 0
Reputation: 15545
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, e.g.
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.
Upvotes: 2