1

I want to plot my network graph with Networkx lib. This is my code:

import networkx as nx

analysis_graph = nx.Graph()

node_list = ["A", "B", "C", "D", "E", "F"]

analysis_graph.add_nodes_from(node_list)
#print(analysis_graph.nodes())

nx.draw(analysis_graph, with_labels = True)
relation_list = [['A', 'B'],
                 ['A', 'C'],
                 ['B', 'D'],
                 ['C', 'E'],
                 ['D', 'F'],
                 ['E', 'D'],
                 ['C', 'E'],
                 ['B', 'D'],                 
                 ['C', 'F'],
                 ['A', 'E'],
                 ['B', 'C'],                 
                 ['B', 'F'],
                 ['D', 'A']]

analysis_graph = nx.from_edgelist(relation_list)
print(nx.info(analysis_graph))
nx.draw(analysis_graph, with_labels = True)

My code works, but each time when I run it, it plots different graph. Is there a way to plot it the same each time?

enter image description here

enter image description here

taga
  • 3,537
  • 13
  • 53
  • 119

2 Answers2

2

Two thoughts:

Is it different if you call draw() twice in a row in the same Python invocation? Which Python version are you using? I wonder if you're using Python <3.6, and this is the result of nondeterministic dict ordering.

The other thing to look into is how networkx uses randomness in drawing. You might need to seed the random number generator:

https://github.com/networkx/networkx/blob/ead0e65bda59862e329f2e6f1da47919c6b07ca9/doc/reference/randomness.rst

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
  • Im using Python 3.8 – taga Sep 23 '21 at 17:30
  • Can you show me how to implement the random number in my code so that I always get the same graph? – taga Sep 23 '21 at 17:36
  • 2
    Take a look at https://stackoverflow.com/questions/49425881/random-seed-doesnt-work-when-provided-and-some-functions-dont-accept-the-seed Basically, add `random.seed(42); np.random.seed(42)` – David Ehrmann Sep 23 '21 at 21:27
1
analysis_graph.add_edges_from(relation_list)

dict_of_node_sizes = dict(analysis_graph.degree) # for getting node sizes
#print(d)
my_pos = nx.spring_layout(analysis_graph, seed = 0) # for giving same graph each time

print(nx.info(analysis_graph))
plt.figure(figsize=(25,17))
nx.draw(analysis_graph, pos = my_pos, with_labels = True, node_size=[v * 100 for v in dict_of_node_sizes.values()])
taga
  • 3,537
  • 13
  • 53
  • 119