Search code examples
pythonnodesnetworkxedges

Is it possible to mix different shaped nodes in a networkx graph?


I have an XML file with two different types of node (let's call it node 'a' and node 'b'). They are connected. I want to present node 'a' as - let's say a square, and node 'b' as a circle. Is this possible in networkx and Python?

My original plan was to declare two graphs:

AG=nx.DiGraph()
BG=nx.DiGraph()

Then add nodes to each of these depending on what type of node it is - so I would iterate through the XML and if the node was a 'type a', then add it to AG and if it is a type B add it to BG

Now I can display each graph and define its' shape - typically:

nx.draw_networkx(EG, font_family="Arial", font_size=10,
                 node_size=2000, node_shape="s", node_color='r', labels=node_labels, with_labels=True)

The part where it falls over is when I try to add edges between an 'a' node and a 'b' node.

Any ideas on how that might work?


Solution

  • Keep the entire dataset in one Graph:

    G = nx.DiGraph()
    

    Also keep lists of A_nodes, and B_nodes. Then you can select subgraphs of G using

    AG = G.subgraph(A_nodes)
    BG = G.subgraph(B_nodes)
    

    Since all the nodes are in G, you can now add edges between A-nodes and B-nodes:

    G.add_edge(a_node, b_node)