'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?

Solution 1:[1]
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.
Solution 2:[2]
Another example, combining graph with bipartite graph:
G = nx.read_edgelist('file.txt', delimiter="\t")
aux = G.edges(data=True)
B = nx.Graph()
B.add_nodes_from(list(employees), bipartite=0)
B.add_nodes_from(list(movies), bipartite=1)
B.add_edges_from(aux)
%matplotlib notebook
import [matplotlib][1].pyplot as plt
plt.figure()
edges = B.edges()
print(edges)
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_networkx(B, pos=pos, edges=edges)
plt.show()
Solution 3:[3]
Inspired in mdml's answer, another way to plot a complete bipartite graph in a "classical" way:
import networkx as nx
import matplotlib.pyplot as plt
m, n = 5, 10
K = nx.complete_bipartite_graph(m, n)
pos = {}
pos.update((i, (i - m/2, 1)) for i in range(m))
pos.update((i, (i - m - n/2, 0)) for i in range(m, m + n))
fig, ax = plt.subplots()
fig.set_size_inches(15, 4)
nx.draw(K, with_labels=True, pos=pos, node_size=300, width=0.4)
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JoseOrtiz3 |
| Solution 2 | Marcelo |
| Solution 3 |


