Search code examples
pythongraphnetworkxgraph-visualization

how can I visual a dense graph obviously in networkx python package?


I have a large, dense directed graph in python, made with the NetworkX package. How can I improve the clarity of the graph image?

The following image shows my graph. enter image description here


Solution

  • I can recommend you several ways to improve your graph visualization depending on its size.


    If you want to visualize a large graph (>1000 nodes), you can read some tricks in my another answer. In your case I recommend you to import the graph to a large vector picture:

    import networkx as nx 
    import matplotlib.pyplot as plt 
    fig = plt.figure(figsize=(40, 40)) 
    G = nx.fast_gnp_random_graph(300, 0.02, seed=1337) 
    nx.draw(G, node_size=30) 
    plt.axis('equal') 
    plt.show() 
    fig.savefig('waka.svg') 
    

    If you have relatively small graph (<1000 nodes), you can play with graph layouts.

    The most suitable layout for your kind of graph is the default spring_layout. It has k argument that set the optimal distance between nodes. Here is the example:

    Default k value

    import networkx as nx
    import random
    random.seed(1234)
    G = nx.fast_gnp_random_graph(30, 0.4, seed=1337)
    for i in range(20):
        G.add_edge(i + 40, random.randint(1, 30))
        G.add_edge(i + 40, random.randint(1, 30))
    pos = nx.spring_layout(G, seed=4321)
    nx.draw(G, pos=pos, node_size=30, node_color='red')
    

    enter image description here

    Enlarged k value

    import networkx as nx
    import random
    random.seed(1234)
    G = nx.fast_gnp_random_graph(30, 0.4, seed=1337)
    for i in range(20):
        G.add_edge(i + 40, random.randint(1, 30))
        G.add_edge(i + 40, random.randint(1, 30))
    pos = nx.spring_layout(G, seed=4321, k=2)
    nx.draw(G, pos=pos, node_size=30, node_color='red')
    

    enter image description here

    It is less readable if you need analyse edges with high precision, but it is better if you are care more about nodes.