Reputation: 605
I want to make a bipartite graph using networkx. I am following documentation and this previous answer
df = pd.DataFrame({'Name': ['John','John','Aron','Aron','Jeny','Jeny'],
'Movie':['A','B','C','A','Y','Z']})
G = nx.Graph()
G.add_nodes_from(df.Name, bipartite=0)
G.add_nodes_from(df.Movie, bipartite=1)
G.add_edges_from(df.values)
Because my graph is disconnected, i.e.
nx.is_connected(G)
>False
top = nx.bipartite.sets(G)[0]
>AmbiguousSolution
I follow documentation as:
top_nodes = {n for n, d in G.nodes(data=True) if d["bipartite"] == 0}
Z = nx.bipartite.projected_graph(G, top_nodes)
nx.draw(Z)
I get:
I expected:
Upvotes: 3
Views: 1157
Reputation: 15505
I can't reproduce your issue. I copied your code and got the correct graph.
>>> import networkx as nx
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> G = nx.Graph()
>>> G.add_nodes_from(df.Name, bipartite=0)
>>> G.nodes
NodeView(('John', 'Aron', 'Jeny'))
>>> G.add_nodes_from(df.Movie, bipartite=1)
>>> G.nodes
NodeView(('John', 'Aron', 'Jeny', 'A', 'B', 'C', 'Y', 'Z'))
>>> G.add_edges_from(df.values)
>>> G.edges
EdgeView([('John', 'A'), ('John', 'B'), ('Aron', 'C'),
('Aron', 'A'), ('Jeny', 'Y'), ('Jeny', 'Z')])
>>> nx.draw(G, with_labels=True)
>>> plt.show()
You can force the positions of the nodes to follow the bipartite nature of the graph, following this answer:
>>> people={n for n,d in G.nodes(data=True) if d['bipartite']==0}
>>> movies=set(G) - people
>>> pos = {n: (1,i) for i,n in enumerate(people)}
>>> pos.update({n: (2,i) for i,n in enumerate(movies)})
>>> nx.draw(G, with_labels=True, pos=pos)
>>> plt.show()
Or this answer:
>>> people={n for n,d in G.nodes(data=True) if d['bipartite']==0}
>>> nx.draw(G, pos=nx.bipartite_layout(G, people), with_labels=True)
>>> plt.show()
Upvotes: 1
Reputation: 2936
Using:
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"Name": ["John", "John", "Aron", "Aron", "Jeny", "Jeny"],
"Movie": ["A", "B", "C", "A", "Y", "Z"],
}
)
G = nx.Graph()
G.add_nodes_from(df.Name, bipartite=0)
G.add_nodes_from(df.Movie, bipartite=1)
G.add_edges_from(df.values)
pos = nx.bipartite_layout(G, df.Name)
nx.draw(G, pos=pos, with_labels=True)
I get:
Please be aware that each time you generate a graph it will sort nodes randomly
Upvotes: 2