【问题标题】:Make a bipartite graph in networkx在networkx中制作二分图
【发布时间】:2022-01-05 02:49:55
【问题描述】:

我想使用 networkx 制作一个二分图。我关注documentationthis 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)

因为我的图表是断开的,即

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)

我明白了:

我预计:

【问题讨论】:

    标签: python graph networkx graph-theory


    【解决方案1】:

    使用:

    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)
    

    我明白了:

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-06
        • 2022-09-27
        • 2013-10-13
        相关资源
        最近更新 更多