Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show node name in graphs using networkx? [duplicate]

I have the code

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])

nx.draw(G)
plt.savefig("graph.png")
plt.show()

And it draws the following graph: enter image description here

However, I need to display labels. How do I display the numeric values and words (one, two, three and four) within the nodes of the graph?

like image 794
macabeus Avatar asked Oct 01 '15 18:10

macabeus


People also ask

How do you duplicate a node in Python?

1. Select the node or nodes you want to clone. 2. In the Node Graph, select Edit > Clone.

What is Nbunch in NetworkX?

nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.

Which data type can be used as the content of a node in NetworkX?

In NetworkX, nodes can be any hashable object e.g., a text string, an image, an XML object, another Graph, a customized node object, etc. Python's None object is not allowed to be used as a node.


1 Answers

You just need to call the with_labels=True parameter with nx.Draw():

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()

G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3)])

nx.draw(G,with_labels=True)
plt.savefig("graph.png")
plt.show()

You can also call font_size, font_color, etc.

See the documentation here: https://networkx.github.io/documentation/latest/reference/drawing.html

like image 170
ryanmc Avatar answered Oct 02 '22 02:10

ryanmc