Search code examples
python-3.xmatplotlibnodesnetworkxedges

Correctly specifying graph using NetworkX (error: Node 'A' has no position)


I'm new to `NetworkX and I was wondering if it's possible to graph nodes that are letters, instead of numbers?

Currently I get this error.

NetworkXError: Node 'A' has no position

I'm using the code that "should" work with numbers.

What changes should I do? I don't find documentation regarding this matter.

Thanks!

    import networkx as nx

    
    # Nodes and edges
    nodos = [("A"),("B"),("C"),("D"),("E"),("F"),("G"),("H"),("I"),("J"),("K")]
    aristas= [("A","B"),("A","C"),("C","D"),("D","F"),("D","G"),("G","H"),("H","I"),("H","J"),("H","K"),("L","E")]
    
    
    G = nx.Graph()
    
    %matplotlib inline
    
    
    graph_pos = nx.spring_layout(G)
    
    nx.draw_networkx_nodes(G, graph_pos, nodos, node_size=400, node_color='blue', alpha = 0.6)
    
    nx.draw_networkx_labels(G, graph_pos, font_size=12, font_family='sans-serif')
    
    nx.draw_networkx_edges(G, graph_pos, edgelist=aristas, edge_color='green', alpha=0.5)

Solution

  • Your code is almost correct, but it's missing the actual addition of nodes and edges:

    # make sure to add the data to the graph
    G.add_nodes_from(nodos)
    G.add_edges_from(aristas)
    

    Here's the full snippet:

    import networkx as nx
    
    # Nodes and edges
    nodos = [("A"), ("B"), ("C"), ("D"), ("E"), ("F"), ("G"), ("H"), ("I"), ("J"), ("K")]
    aristas = [
        ("A", "B"),
        ("A", "C"),
        ("C", "D"),
        ("D", "F"),
        ("D", "G"),
        ("G", "H"),
        ("H", "I"),
        ("H", "J"),
        ("H", "K"),
        ("L", "E"),
    ]
    
    
    G = nx.Graph()
    
    # make sure to add the data to the graph
    G.add_nodes_from(nodos)
    G.add_edges_from(aristas)
    
    graph_pos = nx.spring_layout(G)
    
    nx.draw_networkx_nodes(G, graph_pos, nodos, node_size=400, node_color="blue", alpha=0.6)
    
    nx.draw_networkx_labels(G, graph_pos, font_size=12, font_family="sans-serif")
    
    nx.draw_networkx_edges(G, graph_pos, edgelist=aristas, edge_color="green", alpha=0.5)