pythonnetgraph

setting seed in multigraph function from netgraph module in python


can we set seed into multigraph function from netgraph module in python? i have tried set seed with this code but it keeps changing everytime i run the code.

import networkx as nx
import matplotlib.pyplot as plt
from netgraph import MultiGraph
import pandas as pd

G = nx.MultiDiGraph()
G.add_node('Surabaya')
G.add_node('Yogyakarta')
G.add_node('Bali')
G.add_node('Semarang')
G.add_node('Medan')
G.add_node('Makassar')
G.add_node('Padang')
G.add_node('Palembang')
G.add_node('Jakarta')
G.add_node('Bandung')

df = pd.read_csv("data.csv")
for x,y,z in zip(df['Asal'],df['Tujuan'],df['Ongkos']):
    G.add_edge(str(x), str(y), weight=z)

plt.figure(figsize=(12,12))
MultiGraph(
    G,
    node_labels=True,
    node_color="skyblue",
    node_size=4.25,
    node_label_fontdict=dict(fontsize=8),
    edge_color="gray",
    edge_labels=nx.get_edge_attributes(G, 'weight'),
    edge_label_fontdict=dict(fontsize=9),
    arrows=True
)
plt.show()

Solution

  • The default node layout in Netgraph is the spring layout (i.e. the Fruchterman-Reingold layout), which is initialized and computed using Numpy functions. Therefor in theory, setting the Numpy seed with np.random.seed(my_seed : int) before plotting should result in reproducible node layouts. However, in practice, the system of attractive and repulsive forces is so complex that the limits in the numerical precision result in significant differences after a few iterations -- in particular for large graphs. Other layouts do not involve as many iterations, nor a similarly complex system of forces, and should be much more reproducible.

    Do note that you can always set the node positions explicitly as described here, which for a small geographical network such as in your example is probably the better choice.

    ...
    city_to_lat_lon = {
        Surabaya : (-7.245833, 112.737778),
        ...      : ...,
    }
    
    MultiGraph(G, node_layout=city_to_lat_lon, ...)