pythonplotgraphnetworkxgraph-layout

How to display a network with better separation using the Networkx package?


I created a graph object using the pytextrank package like so:

import pytextrank
### ........................... 
### Some steps and calculations
### ...........................
graph, ranks = pytextrank.text_rank(path_stage1)

And I can use the networkx package to make a networkx drawing like so:

import networkx as nx
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(50,50))
nx.draw(graph, with_labels=True) 

plt.show()

enter image description here

But as you can see, the words are mostly concentrated around the center. I would like to see higher separation between classes of words. How do I do that?


Solution

  • What you are looking for is a different layout (Networkx's term for node positioning algorithms that are used when drawing graphs). By default, nx.draw() is using spring layout. Changing your layout can be done as follows:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(50,50))
    pos = nx.spectral_layout(graph)
    nx.draw(graph, pos=pos, with_labels=True) 
    
    plt.show()
    

    You can play with a few layouts to find one that suits your needs.

    Another option is to save your graph to a file, and load it with gephi, which has a nice GUI for visualizing and exploring your graph. (Also supporting several graph layout algorithms).