John Abbrams
John Abbrams

Reputation: 17

How to draw custom graphs and add labels to vertices in Python?

I am trying to draw a graph in which obviously I have vertices and edges.

I managed to create the graph itself, but I would like to modify the code in such a way, that every vertex has a label. Like"A,B,C,D". I would like to be able to draw the graph given user's input (if you can help me like that).

Minimal working input/output: Input:

4 (number of nodes)
4 (number of edges)
1 2 2 3 1 3 2 4 (the pairs of connected vertices)

Output:

enter image description here

My code that prints a graph with no labels (the edges are given in

import numpy as np   
import networkx as nx  
import matplotlib.pyplot as plt

G=nx.Graph()

G.add_edges_from([(1,2),(2,3),(1,3),(2,4)])
nx.draw(G,vertex_label=["A", "B", "C", "D"]) 
plt.show()

Upvotes: 1

Views: 2632

Answers (1)

unutbu
unutbu

Reputation: 879103

import numpy as np   
import networkx as nx  
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from([(1,2),(2,3),(1,3),(2,4)])
labelmap = dict(zip(G.nodes(), ["A", "B", "C", "D"]))
nx.draw(G, labels=labelmap, with_labels=True) 
plt.show()

yields an image such as enter image description here

Upvotes: 3

Related Questions