【问题标题】:Draw topological ordered graph with curved edges绘制具有弯曲边的拓扑有序图
【发布时间】:2020-06-09 16:34:00
【问题描述】:

我正在尝试在 python 中使用 networks.draw() 函数绘制图形。尽管它不是有向图,但我以拓扑排序顺序排列了图的边缘。我想打印看起来像依赖 DAG 的图形以获得更好的可见性。目标是这样的:

我应该怎么做?

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    使用如下示例边列表,并构建无向图:

    edges = [[1,3], [1,4], [1,5], [5,7], [5,8] ,[5,9],
             [9,11], [9,12], [9,13], [2,4], [6,8] ,[10,12]]
    
    G = nx.Graph()
    G.add_edges_from(edges)
    

    我们可以使用节点名来定义一个字典,将节点名映射到一行,其中x坐标与节点名相同。现在获得带有弯曲边缘的精美布局是棘手的部分。虽然这是必要的,否则边缘会相互重叠。这可以使用matplotlib.axes.Axes.annotate 来完成。

    请注意,我假设在 even 节点编号处具有源的边具有 positive 符号弧,否则为负,如果不是这种情况,则应该是很容易适应:

    pos = {node:(node,0) for node in G.nodes()}
    
    plt.figure(figsize=(15,5))
    ax = plt.gca()
    for edge in edges:
        source, target = edge
        rad = 0.8
        rad = rad if source%2 else -rad
        ax.annotate("",
                    xy=pos[source],
                    xytext=pos[target],
                    arrowprops=dict(arrowstyle="-", color="black",
                                    connectionstyle=f"arc3,rad={rad}",
                                    alpha=0.6,
                                    linewidth=1.5))
    nx.draw_networkx_nodes(G, pos=pos, node_size=500, node_color='black')
    nx.draw_networkx_labels(G, pos=pos, font_color='white')
    plt.box(False)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多