Search code examples
pythonnetworkx

NetworkX does not show edge label for edge to the same node


I discovered a strange behavior with the NetworkX graph drawing library: it does not draw the edge label if the edge leads backwards to the same node.

I'm pretty sure that it is a NetworkX feature, because I create all the edge labels with the same method and it works fine with non-looping edges, as you can see in the image.

Is there any display option that can help to display all edge labels?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()

edge_labels = dict()

g.add_edge(0, 1 )
#ATTENTION - this will work
edge_labels[(0, 1)] = '01'

g.add_edge(0, 0)

#ATTENTION - this line will not work
edge_labels[(0, 0)] = '00'

pos = nx.spring_layout(g)
nx.draw(g, pos, with_labels=True, font_weight='bold')
nx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels, 
font_color='red')
plt.show()

Solved by putting '_____' before the string for the looping edge, it is how you can see it. Is not pretty, but displays

        if state_id == self.last_parent.id:#if it is loop
        self.edge_labels[(self.last_parent.id, state_id)] = '_____'+ char_of_edge# add to the edge label the symbols

Example:

Image example


Solution

  • Given the coordinates of two nodes (x1, y1) and (x2, y2) the label position is computed as

    (x, y) = (
                x1 * label_pos + x2 * (1.0 - label_pos),
                y1 * label_pos + y2 * (1.0 - label_pos),
            )
    

    where label_pos has a default value of 0.5 [source].
    This means that the edge label for a self-edge overlaps with the node position and this is why you cannot see it, unless increasing the font size.