我想用networkx制作二部图。我正在跟踪文档和这个先前的答案
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)因为我的图是断开的,也就是
nx.is_connected(G)
>False
top = nx.bipartite.sets(G)[0]
>AmbiguousSolution 我将文件记录如下:
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)我得到:

我期望:

发布于 2021-11-27 13:09:47
使用:
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)我得到:

请注意,每次生成图时,它都会对节点进行随机排序。
发布于 2021-11-27 13:06:31
我不能重复你的问题。我复制了你的代码得到了正确的图表。
>>> 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()

您可以强制节点的位置遵循图的二分性质,遵循这个答案
>>> 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()

或这个答案
>>> 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()

https://stackoverflow.com/questions/70134625
复制相似问题