Beginner Prog
Beginner Prog

Reputation: 39

networkx draw separate nodes to left and right side - graphviz, python

I use the following code to colour the nodes that start with "n" as gray and the nodes starting with "m" letter with red colour

color_map = []
    for node in c:
        strnode = str(node)
        if strnode.startswith("m"):
            color_map.append('red')
        else:
            color_map.append('gray')

    nx.draw(c, pos=nx.nx_agraph.graphviz_layout(c, prog='circo'),node_size=140,  scale= 2,  node_color=color_map,with_labels=True)

This works successfully as the picture shows below:

enter image description here

However, I have tried to draw the graph as a bipartite graph, meaning all the Red nodes to be aligned on the left side and all the gray nodes on the left side with no success. Any ideas?

*Fixed with @Mohammed Kashif answer, however the right side notes cannot displayed all:

enter image description here

Upvotes: 2

Views: 2209

Answers (1)

Gambit1614
Gambit1614

Reputation: 8811

You can use bipartite_layout defined in NetworkX. You can read more about it here. You need to pass a list of nodes belonging to either of the sets of the bipartite layout.

Below is the working example which uses the bipartite_layout. I took the liberty of defining the nodes of the Graph similar to yours.

import networkx as nx

# Define the nodes of the Graph
nodes_list = ["m1", "n1", "m2", "n2", "m3", "n3", "m4", "n4"]

# Define the Graph and add the nodes/edges
G = nx.DiGraph()
G.add_nodes_from(nodes_list)
G.add_edges_from([("m1", "n3"), ("m2", "n1"), ("n4", "m3")])


color_map = []

# This will store the nodes belonging to one set of 
# the bipartite graph. In this case, the nodes which
# start with "m"
one_side_nodes = []

for node in G:
    strnode = str(node)
    if strnode.startswith("m"):
        color_map.append('red')
        # Add the node to the list
        one_side_nodes.append(node)
    else:
        color_map.append('gray')

# Now in the `pos` attribute pass in nx.bipartite_layout,
# with the list of nodes belonging to one set of the bipartite
# graph, i.e. one_side_nodes.
nx.draw(G, pos=nx.bipartite_layout(G, one_side_nodes),node_size=140,
        scale= 2, node_color=color_map, with_labels=True)

Here is the output:

Bipartite Layout

References:

You can also view the code on Google Colab Notebook here.

Upvotes: 3

Related Questions