【问题标题】:Bipartite graph in NetworkXNetworkX 中的二分图
【发布时间】:2015-01-20 22:27:08
【问题描述】:
B.add_nodes_from(a, bipartite=1)
B.add_nodes_from(b, bipartite=0)
nx.draw(B, with_labels = True)  
plt.savefig("graph.png")

我得到下图。我怎样才能使它看起来像一个适当的二部图?

【问题讨论】:

    标签: python matplotlib networkx bipartite


    【解决方案1】:

    NetworkX 已经有一个功能可以做到这一点。

    它叫networkx.drawing.layout.bipartite_layout

    您可以使用它来生成字典,该字典通过 pos 参数提供给像 nx.draw 这样的绘图函数,如下所示:

    nx.draw_networkx(
        B,
        pos = nx.drawing.layout.bipartite_layout(B, B_first_partition_nodes), 
        width = edge_widths*5) # Or whatever other display options you like
    

    B 是完整的二分图(表示为常规 networkx 图),B_first_partition_nodes 是您希望放置在第一个分区中的节点。

    这会生成一个数字位置字典,并传递给绘图函数的pos 参数。您也可以指定布局选项,请参阅main page

    强制性示例输出:

    【讨论】:

      【解决方案2】:

      另一个例子,图与二分图的结合:

      G = nx.read_edgelist('file.txt', delimiter="\t")
      aux = G.edges(data=True)
      B = nx.Graph()
      B.add_nodes_from(list(employees), bipartite=0)
      B.add_nodes_from(list(movies), bipartite=1)
      B.add_edges_from(aux)
      
      %matplotlib notebook
      import [matplotlib][1].pyplot as plt
      plt.figure()
      
      edges = B.edges()
      print(edges)
      X, Y = bipartite.sets(B)
      pos = dict()
      pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
      pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
      nx.draw_networkx(B, pos=pos, edges=edges)
      plt.show()
      

      【讨论】:

        【解决方案3】:

        您可以这样做,从每个分区中的特定x 坐标处绘制节点:

        X, Y = bipartite.sets(B)
        pos = dict()
        pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
        pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
        nx.draw(B, pos=pos)
        plt.show()
        

        关键是为nx.drawpos参数创建dict,即:

        以节点为键、位置为值的字典。

        the docs

        【讨论】:

          猜你喜欢
          • 2022-01-05
          • 2022-09-27
          • 2011-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多