pygraphviz:添加{rank = same; node1 node2}

时间:2019-02-28 00:01:07

标签: graphviz rank pygraphviz

我没有看到在pygraphviz中添加相同排名的示例。现在,我使用G.string()字符串,并在其末尾附加{rank = same; node1 node2}。有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

在我的代码中,add_nodes_from()在相同的水平级别添加了没有边的节点:

A.add_nodes_from(["coyote", "wolf"])

add_edge()添加了在垂直列中具有边的节点:

A.add_edge(1,2)

设置参数constraint=False将节点置于相同的水平位置:

A.add_edge(previous_item, item, rank='same', constraint=False)

我写了一个函数:

def add_nodes_connected_by_edges(graph, items, rank_same):
    """
    Adds nodes to graph, one node per string in items
    :param graph: a pygraphviz graph
    :param items: a list of strings
    :param rank_same: boolean. True ranks nodes so they appear at same horizontal level
    """
    previous_item = None

    for item in items:
        graph.add_node(item)
        if previous_item is not None:
            # Use constraint=False to keep rank same
            # https://stackoverflow.com/questions/22756929/graphviz-make-edges-not-affecting-the-hierarchy-of-nodes
            graph.add_edge(previous_item, item, rank='same', constraint=(not rank_same))

        previous_item = item

graphvizzy存储库显示了更完整的示例pygraphviz nodes