2

I want to create an undirected graph, using DiGraph of networkx. I want different labels on the edges for opposite edges. My code is:

G = nx.DiGraph()

nodes = [1, 2, 3]
edges = [
    (1, 2, {"label": "1-2"}), 
    (2, 3, {"label": "2-3"}), 
    (3, 1, {"label": "3-1"})
]

G.add_nodes_from(nodes)
G.add_edges_from(edges)
edge_labels = nx.get_edge_attributes(G,'label')

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos=pos)
nx.draw_networkx_labels(G, pos=pos)
nx.draw_networkx_edges(G, pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.show()

enter image description here

But I want to add another edge, for example from node 1 to 3, with different label. I tried to add the edge (1, 3, {"label": "1-3"}). It just make the edge from 3 to 1 to be directed, and ignore the label. So the output is: enter image description here

edit: So I found that the solution is much easier using directly graphviz. My code is:

from graphviz import Digraph

G = Digraph('G')

G.attr('graph', pad='1', ranksep='1', nodesep='1')
G.attr('node', shape='note')

G.node('A', 'A')
G.node('B', 'B')
G.node('C', 'C')

G.edge('A', 'B', 'A-B')
G.edge('B', 'A', 'B-A')
G.edge('A', 'C', 'A-C')
G.edge('C', 'A', 'C-A')
G.edge('B', 'C', 'B-C')
G.edge('C', 'B', 'C-B')

G.view()

Which is output as expected: enter image description here
Thanks for everyone who tried to help :)

Shahar
  • 33
  • 4
  • 1
    It is currently not possible to draw from `networkx` using `matplotlib` edges that are *both* curved and labeled, which is what would be needed here to avoid the overlap between opposite edges, which hides labels. It is possible to draw directed and labeled multi-graphs with `networkx` and GraphViz, as described at: https://stackoverflow.com/a/67238706/1959808 – 0 _ Apr 24 '21 at 02:08

2 Answers2

1

You can use a MultiDiGraph:

A directed graph class that can store multiedges.

Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.

A MultiDiGraph holds directed edges. Self loops are allowed.

So simply change to:

G = nx.MultiDiGraph()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
darth baba
  • 1,277
  • 5
  • 13
0

The edges can be separated by adding connectionstyle='arc3, rad=0.1', but the edge labels cannot be separated in the same way:

nx.draw_networkx_edges(G, pos=pos, connectionstyle='arc3, rad=0.1')
Mohammad Rahmani
  • 364
  • 1
  • 3
  • 11