【问题标题】:How to use nested dictionary to draw networkx tree graph?如何使用嵌套字典绘制networkx树图?
【发布时间】:2022-01-19 18:40:21
【问题描述】:

我有一本这样的字典:

{
        "dashboard": {
            "dashboard": {
                "data": {
                    "data": {
                        "content": {}
                    }
                },
            }
        },
        "docs": {
            "docs": {
                "content": {},
                "analytics": {}
            }
        }
    }

我想用这本字典来画一个networkx树形图。由于有多个根,我可以绘制多个图而不是一个图吗?例如,“仪表板”和“文档”的两个单独图表。我面临的另一个问题是我无法将字典直接用于networkx。直到现在我发现 readwrite.json_graph.tree_graph() 可以读取这样的字典对象并生成图形。但问题是我需要更改格式。我怎样才能使以前的字典如下所示:

    {
        {
        "id": "dashboard", 
        "children":[{
            "id": "dashboard",
            "children":[{
                "id": "data",
                "children":[{
                    "id": "data",
                    "children":[{
                        "id": "content"
                        }]
                    }]
                }]
            }]
        }
        {
        "id": "docs",
        "children":[{
            "id": "docs",
            "children":[{
                "id": "content",
                "id": "analytics"
                }]
            }]
        }
    }

我试过这段代码来改变格式:

        def translate(d, p, r):
            for k, v in d.items():
                # if k not in p:
                r = {
                    'id': k,
                    'children' if isinstance(v, dict) else None: translate(v, p, r)
                }
            return r

        result = translate(all_items, has_parent, r={})
        return result

【问题讨论】:

  • 图表与您的代码有何关系?我没有得到您试图从嵌套字典中捕获的关系结构(networkx 适用于字典字典,而不是几层字典),并且该图不代表您的字典(“仪表板”缺失和“混合”不存在)。
  • 该图只是一个示例。该图显示了调用的路径。

标签: python python-3.x dictionary networkx


【解决方案1】:

您不需要更改原始字典的结构,您可以在创建图表时构建标签:

import matplotlib.pyplot as plt
import networkx as nx
import itertools as it
d, c, d1 = {}, it.count(1), {}
g = nx.Graph()
data = {'dashboard': {'dashboard': {'data': {'data': {'content': {}}}}}, 'docs': {'docs': {'content': {}, 'analytics': {}}}}
def build_graph(g, v, p=None):
   for a, b in v.items():
      if a not in d:
         d[a] = next(c)
      g.add_node(d[a])
      if p is not None:
         g.add_edge(p, d[a])
      build_graph(g, b, p=d[a])

for a, b in data.items():
   build_graph(g, {a:b})   
   d1.update({y:x for x, y in d.items()})
   d = {}

nx.draw(g, labels=d1, with_labels = True)
plt.show()  

结果:

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 1970-01-01
    • 2021-10-09
    • 2015-03-06
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2022-10-18
    • 2018-01-21
    相关资源
    最近更新 更多