【问题标题】:NetworkX: draw graph in layersNetworkX:分层绘制图形
【发布时间】:2017-07-06 07:49:44
【问题描述】:

我有一个按级别划分的图表,即 f.e. :

ids : 0 - 100 are lowest level
ids : 101 - 500 are level 2
ids : 501 - 1500 are level 3
and so on ...

是否有某种方法可以强制图表在按层组织的级别中绘制节点,一个在另一个之上。

我想将它们堆叠起来而不会溢出:)

在我的情况下,节点位于哪一层取决于节点 ID,但如果您有一些想法,它可能是其他一些组织原则。


到目前为止,这似乎是可能的解决方案:

def plot(self):
    plt.figure()
    pos = nx.graphviz_layout(self.g,prog='dot')
    nx.draw(self.g, pos, node_size=650, node_color='#ffaaaa')

五层示例 ...

【问题讨论】:

  • 您能发布一个具有所需结果的示例图像吗?
  • 我知道这是一个老问题,但我为最近的一个类似问题 here 提供了解决方案。

标签: python networkx


【解决方案1】:

【讨论】:

    【解决方案2】:

    你考虑过https://github.com/SkBlaz/Py3Plex吗?它对多层网络有适当的支持。

    【讨论】:

      【解决方案3】:

      布局函数,例如nx.spring_layout,返回一个dict,其键是节点,值是2元组(坐标)。以下是pos dict 的示例:

      In [101]: pos
      Out[101]: 
      {(0, 0): array([ 0.70821816,  0.03766149]),
       (0, 1): array([ 0.97041253,  0.30382541]),
       (0, 2): array([ 0.99647583,  0.63049339]),
       (0, 3): array([ 0.86691957,  0.86393669]),
       (1, 0): array([ 0.79471631,  0.08748146]),
       (1, 1): array([ 0.71731384,  0.35520076]),
       (1, 2): array([ 0.69295087,  0.71089292]),
       (1, 3): array([ 0.63927851,  1.        ]),
       (2, 0): array([ 0.42228877,  0.        ]),
       (2, 1): array([ 0.33250362,  0.3165331 ]),
       (2, 2): array([ 0.31084694,  0.69246818]),
       (2, 3): array([ 0.34141212,  0.9952164 ]),
       (3, 0): array([ 0.16734454,  0.11357547]),
       (3, 1): array([ 0.01560951,  0.33063389]),
       (3, 2): array([ 0.        ,  0.63044189]),
       (3, 3): array([ 0.12242227,  0.85656669])}
      

      然后,您可以以任何您喜欢的方式进一步操作这些坐标。例如,由于 spring_layout 返回的 xy 坐标在 0 和 1 之间,你 可以将层级值的 10 倍添加到y-坐标以将节点分成层:

      for node in pos:
          level = node // nodes_per_layer
          pos[node] += (0,10*level)
      

      import networkx as nx
      import matplotlib.pyplot as plt
      
      layers = 5
      nodes_per_layer = 3
      n = layers * nodes_per_layer
      p = 0.2
      
      G = nx.fast_gnp_random_graph(n, p, seed=2017, directed=True)
      pos = nx.spring_layout(G, iterations=100)
      
      for node in pos:
          level = node // nodes_per_layer
          pos[node] += (0,10*level)
      
      nx.draw(G, pos, node_size=650, node_color='#ffaaaa', with_labels=True)
      plt.show()
      

      产生

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-21
        • 2013-08-03
        相关资源
        最近更新 更多