Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bipartite graph in NetworkX

B.add_nodes_from(a, bipartite=1)
B.add_nodes_from(b, bipartite=0)
nx.draw(B, with_labels = True)  
plt.savefig("graph.png")

I am getting the following figure. How can I make it look like a proper bipartite graph?

My graph

like image 646
sheetal_158 Avatar asked Nov 23 '14 00:11

sheetal_158


People also ask

Is NetworkX graph bipartite?

NetworkX does not have a custom bipartite graph class but the Graph() or DiGraph() classes can be used to represent bipartite graphs.

How do you make a bipartite graph?

Let G be a graph with vertex set V(G) and edge set E(G), respectively. The set of vertices adjacent to an x E V(G) is denoted by T(x), and the degree of x is d(x) = 1 I'(x)l. For any subset v' L V(G), let G[ V'] denote the subgraph of G induced by the vertices of I/'.


2 Answers

You could do something like this, to draw nodes from each partition at a particular x coordinate:

X, Y = bipartite.sets(B)
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
nx.draw(B, pos=pos)
plt.show()

bipartite-graph

The key is creating the dict for the the nx.draw pos parameter, which is:

A dictionary with nodes as keys and positions as values.

See the docs.

like image 154
mdml Avatar answered Sep 21 '22 18:09

mdml


NetworkX already has a function to do exactly this.

Its called networkx.drawing.layout.bipartite_layout

You use it to generate the dictionary that is fed to the drawing functions like nx.draw via the pos argument like so:

nx.draw_networkx(
    B,
    pos = nx.drawing.layout.bipartite_layout(B, B_first_partition_nodes), 
    width = edge_widths*5) # Or whatever other display options you like

Where B is the full bipartite graph (represented as a regular networkx graph), and B_first_partition_nodes are the nodes you wish to place in the first partition.

This generates a dictionary of numeric positions that is passed to the pos argument of the drawing function. You can specify layout options as well, see the main page.

Obligatory example output: enter image description here

like image 44
OrangeSherbet Avatar answered Sep 20 '22 18:09

OrangeSherbet