Reproduce same graph in NetworkX

Viewed 689

I would like to improve my graph. There are problems as follow:

  1. how to create a consistent graph.the graph itself is not consistent everytime i execute / run the code, it will generate different images. The inconsistent graph is shown in the url.

enter image description here

  1. how to customize the whole graph / picture size and to make it bigger
  2. how to set a permanent position for an object 'a' so that it will consistently appears at the first / top position
  3. how to customize length of arrow for each relationship.

Appreciate if anyone could give some notes or advices

This is my codes:

Unique_liss= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']

edgesList= [('a', 'b'), ('b', 'c '), ('c ', 'd'), ('d', 'e'), ('d', 'f'), ('e', 'g'), ('f', 'g'), ('g', 'h'), ('h', 'i '), ('i ', 'j'), ('j', 'k'), ('j', 'l'), ('k', 'm'), ('l', 'm')]

import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(Unique_liss)
g.add_edges_from(edgesList)
nx.to_pandas_adjacency(g)

G = nx.DiGraph()
for node in edgesList:
    G.add_edge(*node,sep=',')

A = nx.adjacency_matrix(G).A

nx.draw(G, with_labels=True, node_size = 2000,
        node_color = 'skyblue')
2 Answers

In order to have deterministic node layouts, you can use one of NetworkX's layouts, which allow you to specify a seed. Here's an example using nx.spring_layout for the above graph:

from matplotlib import pyplot as plt

seed = 31
pos = nx.spring_layout(G, seed=seed)
plt.figure(figsize=(10,6))
nx.draw(G, pos=pos, with_labels=True, node_size = 1500,
        seed=seed, node_color = 'skyblue')

enter image description here

You'll get the exact same layout if you re-run the above.

In order to customize the graph size you have several options. The simplest one baing setting the figure size as plt.figure(figsize=(x,y)) as above. And you can also control the size of the graph within the figure using the scale paramater in nx.spring_layout.

As per the last point, it looks like you cannot set specific arrow sizes for each edge. From the [docs](arrowsize : int, optional (default=10)) what you have is:

arrowsize : int, optional (default=10)

So you can only set this value to an int, which will result in an equal size for all edge arrows.

For anyone who doesn't get to read the comments in answers. I found that as @amj mentions in the components, that on top of @yatu's response above, you need to set the seed in numpy.

import numpy as np 
seed = 31 
np.random.seed(seed)
Related