Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading