繁体   English   中英

在networkx中制作二分图

[英]Make a bipartite graph in networkx

我想使用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)

我得到:

在此处输入图像描述

我期望:

在此处输入图像描述

我无法重现您的问题。 我复制了您的代码并得到了正确的图表。

>>> 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()

二部图 1

您可以按照以下答案强制节点的位置遵循图的二分性质:

>>> 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()

二部图 2

或者这个答案

>>> 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()

二部图 3

使用:

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)

我得到:

在此处输入图像描述

请注意,每次生成图表时,它都会对节点进行随机排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM