Reputation: 1607
I am seeing something weird with the networkx package. Here is a minimal concrete verifiable example.
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edge('A', 'B', weight=1, title='ab', subtitle='testing')
edge_labels = nx.get_edge_attributes(G, 'title')
print(edge_labels)
This gives the expected output, which is the title attribute of the edge.
{('A', 'B'): 'ab'}
When I use the edge_labels for plotting,
fig = plt.figure()
ax1 = plt.subplot2grid((1, 1), (0, 0))
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, labels=edge_labels)
plt.show()
I see the following graph, where all the edge attributes are displayed. I expected only the title to turn up.
The graph I am constructing is a step-by-step process so the edge labels get updated as more information is processed. How do I label the edges with only the attributes I want at the end of the graph construction?
Upvotes: 1
Views: 4786
Reputation: 879591
Use
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
instead of
nx.draw_networkx_edge_labels(G, pos, labels=edge_labels)
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edge('A', 'B', weight=1, title='ab', subtitle='testing')
edge_labels = nx.get_edge_attributes(G, 'title')
print(edge_labels)
fig = plt.figure()
ax1 = plt.subplot2grid((1, 1), (0, 0))
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.show()
yields
Since the call signature for nx.draw_networkx_edge_labels
looks like this:
draw_networkx_edge_labels(G, pos, edge_labels=None, label_pos=0.5,
font_size=10, font_color='k', font_family='sans-serif',
font_weight='normal', alpha=1.0, bbox=None, ax=None, rotate=True, **kwds)
the function expects the labels to be supplied by the keyword parameter edge_labels
. Since the call signature also includes **kwds
, the bogus parameter labels
is swallowed silently, and this piece of code
if edge_labels is None:
labels = dict(((u, v), d) for u, v, d in G.edges(data=True))
generated the "strange" label you were seeing in the result.
Upvotes: 7