簡體   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