Python NetworkX - Why are graphs always randomly rotated?

后端 未结 3 1866
旧巷少年郎
旧巷少年郎 2021-01-13 07:44

If I generate the same graph multiple times using NetworkX and Matplotlib it\'s rotated randomly on every generation:

Run 1:

Run 2:

Without changin

相关标签:
3条回答
  • 2021-01-13 08:18

    From the docs:

    spring_layout(G, dim=2, k=None, pos=None, fixed=None, iterations=50, weight='weight', scale=1.0)
    

    pos : dict or None optional (default=None)

    Initial positions for nodes as a dictionary with node as keys and values as a list or tuple. If None, then use random initial positions.

    So if you don't specify initial positions of your nodes, NetworkX will do so at random.

    https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.drawing.layout.spring_layout.html

    0 讨论(0)
  • 2021-01-13 08:29

    I just found out that you can fix the initial state of the random generated graph: just seed the generator so it will always produce the same set of random positions.

    random_pos = nx.random_layout(graph, seed=42)
    pos = nx.spring_layout(graph, pos=random_pos)
    
    0 讨论(0)
  • 2021-01-13 08:32

    The algorithm has a random initialization - this is quite standard for network layouts. You will have the same issue with any graph library. You can replicate the same layout in NetworkX in two ways: save the node position dictionary (for example as a json) and reload it every time you want to visualize, or pass a seed to the layout algorithm:

    seed (int, RandomState instance or None optional (default=None)) – Set the random state for deterministic node layouts. If int, seed is the seed used by the random number generator, if numpy.random.RandomState instance, seed is the random number generator, if None, the random number generator is the RandomState instance used by numpy.random.

    hope that helps!

    0 讨论(0)
提交回复
热议问题