Drawing a directed graph from a list of nodes with Python

That’s the ending graph that I would like to end up with, but to begin with it would be great to have simply bus late and overslept without considering the alarm on node.

enter image description here

I would like to know how to draw a directed graph on Python starting from a list of nodes. I know that I have to use networkX but I’m having some troubles;

Let’s say that all the nodes from a specific list are linked to another external node, called x, so if I have the list of nodes : nodes = [1,2,3], I will want edges ((1,0),(2,0),(3,0)); How could I draw then this specific graph?

I got stuck here, basically I have created a directed graph I think, but I don’t know how to draw it:


    import networkx as nx
    import matplotlib.pyplot as plt
    
    G = nx.Graph()
    nodes = [1,2,3]
    
    terminal = [0]
    G.add_nodes_from(nodes)
    
    edges = []
    
    for i in range(len(nodes)):
        edges.append((0, nodes[i]))
    
    G.add_edges_from(edges)
    
    H = nx.DiGraph(G)

Furthermore, I want to later use it for a Bayesian Network, any suggestions?

Any help will be greatly appreciated

>Solution :

What about:

import networkx as nx
from itertools import product

nodes = [1, 2, 3]
terminal = [0]

G = nx.from_edgelist(product(nodes, terminal), create_using=nx.DiGraph)

Resulting graph:

nx.draw(G, pos=nx.spring_layout(G), with_labels=True)

Output:

enter image description here

Or with graphviz:

enter image description here

Leave a Reply