Search code examples
pythonpython-3.xnetworkxgraph-visualization

Issue with spacing nodes in networkx graph


I'm trying to make a networkx graph with several hundred edges:

def generate_network_graph(graph):
    visual_graph = networkx.Graph()
    for edge in graph.edges:
        visual_graph.add_edge(edge.actor.name, edge.movie.title)
    plt.figure(3, figsize=(30, 30))
    networkx.spring_layout(visual_graph, k=0.9, iterations=20)
    networkx.draw_spring(visual_graph)
    plt.show()

No matter how much I seem to increase k, however, my graph comes out looking like a clustered mess:

enter image description here

I'm not sure what else to do keep the nodes from overlapping; I've tried a range of k values from 0.0 to 5.0. I thought about decreasing the size of the nodes, but I'm not sure if that would just make the graph less readable. Not only that, but regenerating this graph takes an abysmal amount of time, ~15 minutes. Am I simply not using the right graph library for the job? Or is there something I can modify to make my graph clearer.


Solution

  • From the documentation

    k : float (default=None) Optimal distance between nodes. If None the distance is set to 1/sqrt(n) where n is the number of nodes. Increase this value to move nodes farther apart.

    You can try the following:

    import networkx as nx
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Set an exemple graph
    edge_list = [(1,2),(2,0),(2,4),(3,4)]
    g = nx.Graph(edge_list)
    
    # plot
    pos = nx.spring_layout(g, k=0.3*1/np.sqrt(len(g.nodes())), iterations=20)
    plt.figure(3, figsize=(30, 30))
    nx.draw(g, pos=pos)
    nx.draw_networkx_labels(g, pos=pos)
    plt.show()
    

    Here kis proportional to 1/np.sqrt(len(g.nodes())), thus nodes are still well separated even when the number of nodes increases.