Search code examples
pythonmatplotlibgraphdata-visualizationnetworkx

Plotting Networkx graph in Python


I recently started using networkx library in python to generate and visualize graph plots. I started with a simple code (comprising of 4 nodes) as shown

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edges_from([(1 ,2) , (2 ,3) , (1 ,3) , (1 ,4) ])
nx.draw(G)
plt.show()

When I run the code for two consecutive times, the outputs for same code is as shown in the images (the orientation of the plot is random)

image 1 image 2

Is it possible to generate the output of the plots with the same/fixed orientation?


Solution

  • Per default a spring layout is used to draw the graph. This can have a new orientation each time it is drawn.

    There are also other layouts available.

    enter image description here

    Using e.g. nx.draw_circular or nx.draw_spectral will give you always the same layout.

    You may also define the positions of the nodes using a dictionary, which maps nodenumber to a position.

    import networkx as nx
    import matplotlib.pyplot as plt
    G = nx.Graph()
    G.add_edges_from([(1 ,2) , (2 ,3) , (1 ,3) , (1 ,4) ])
    pos = { 1: (20, 30), 2: (40, 30), 3: (30, 10),4: (0, 40)} 
    
    nx.draw_networkx(G, pos=pos)
    
    plt.show()
    

    enter image description here