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

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

我是 `NetworkX 的新手,我想知道是否可以绘制字母节点而不是数字节点?

目前我收到这个错误。

NetworkXError: Node 'A' has no position

我正在使用“应该”处理数字的代码。

我应该做什么改变?我没有找到关于此事的文档。

谢谢!

    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)

您的代码几乎是正确的,但缺少节点和边的实际添加:

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

这是完整的片段:

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)