Search code examples
pythonnetworkx

NetworkX how to create DiGraph from list of edges with node attributes


I currently have some code that generates a list of edges like this:

# where the edge is of form [node1, node2, edge_attribute_dict]
edges = [[x.text_1, x.text_2, {"label": x.edge_label}] for x in edges]

# generate digraph from edge list
graph = nx.DiGraph(edges)

However, some of the text_1 or text_2 are the same, and only create one node, instead of multiple nodes for each occurrence of the same node text. That's why I'd like to add node attributes at the same time to identify the node, other than the node text.

Something like:

    edges = [[{x.id_1: x.text_1}, {x.id_2: x.text_2}, {"label": x.edge_label}] for x in edges]
    
    # generate digraph from edge list
    graph = nx.DiGraph(edges)

But that doesn't work. Is there a way to do this all at once at the time of the DiGraph generation or do I have to add the nodes and edges one by one with the correct attributes?


Solution

  • The best solution I could find was to have a separate step (nx.draw_networkx_labels(graph, pos, labels=node_label_map)) with a node_label_map, where I use the ids for nodes to create edges, and then map the labels to those ids afterward. Like this:

    edges = [[x.id_1, x.id_2, {"label": x.edge_label}] for x in edges]
    
    # generate node id -> label map
    node_label_map = {x.id: x.text for x in nodes}
    
    # generate digraph from edge list
    graph = nx.DiGraph(edges)
    
    # draw the graph with_labels=False and then passing in node_label_map
    nx.draw(
        graph,
        pos,
        with_labels=False,
    )
    nx.draw_networkx_labels(graph, pos, labels=node_label_map)