Search code examples
pythonplotnetworkx

How do I change the "position" of an edge in networkx?


enter image description here

(Label the nodes as 1 to 4 clockwise starting on the top left)

How do I change the edge 13 to make it go "outside" the square, like the graph on the right, in networkx?

(Note: I am not asking for the function "draw_planar")

Thanks


Solution

  • A possible option would be to use Connection styles for annotations.

    You can start by drawing the nodes in a classic way :

    fig, ax = plt.subplots(figsize=(4, 4))
    
    nx.draw_networkx_nodes(
        G, pos, ax=ax,
        node_color="lime", alpha=0.4, edgecolors="black",
    )
    
    nx.draw_networkx_labels(G, pos, ax=ax)
    

    Then proceed with the edges in two steps, to implement the connectionstyle:

    RADIUS = 1.2
    EDGE_TO_BEND = (1, 3)
    
    nx.draw_networkx_edges(
        G, pos, ax=ax, edgelist=[e for e in G.edges() if e != EDGE_TO_BEND]
    )
    
    nx.draw_networkx_edges(
        G, pos, ax=ax, edgelist=[EDGE_TO_BEND],
        edge_color="tab:red", width=4, alpha=0.5,
        arrows=True, connectionstyle=f"arc3,rad={RADIUS}",
    )
    
    ax.axis("off")
    
    plt.show()
    

    enter image description here

    Graph used (G):

    import networkx as nx
    
    G = nx.Graph([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3), (2, 4)])
    
    pos = {1: (0, 1), 2: (1, 1), 3: (1, 0), 4: (0, 0)} # square-shape