how to print a graph in networkx in python

To print a graph in Networkx in Python, you can use the draw() function from the networkx library and the matplotlib library for plotting. Here's an example:

main.py
import networkx as nx
import matplotlib.pyplot as plt

# Create a graph
G = nx.Graph()

# Add nodes and edges to the graph
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])

# Draw the graph
nx.draw(G, with_labels=True)

# Show the graph
plt.show()
281 chars
16 lines

This will create a simple graph with four nodes and four edges, and then use the draw() function to visualize it. The with_labels=True argument is used to display the node labels on the plot. Finally, plt.show() is used to display the graph plot.

You may need to install networkx and matplotlib libraries if you haven't already done so:

main.py
pip install networkx
pip install matplotlib
44 chars
3 lines

Hope this helps!

related categories

gistlibby LogSnag