Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set NetworkX edge labels offset? (to avoid label overlap)

I am trying to add edge labels for a graph. It all works well, only problem is when the two edges intersect - I only see one of the labels as they happen to overlap.

example

As you can see the hphob-alpha label is shown but the polarity-beta label is not shown (my guess is that it is right under the previously mentioned).

I could not find any documentation on how to re-position the labels, any advice how to set some kind of offset to move the labels?

Code used to generate the graph:

try:
    import matplotlib.pyplot as plt
except:
    raise

import networkx as nx

G=nx.Graph()

a="hphob"
b="polarity"
c="alpha"
d="beta"
G.add_edge(a,b,weight=0.5)
G.add_edge(b,c,weight=0.5)
G.add_edge(c,d,weight=0.5)
G.add_edge(a,d,weight=0.5)
G.add_edge(a,c,weight=0.5)
G.add_edge(b,d,weight=0.5)

pos=nx.spring_layout(G) # positions for all nodes

# nodes
nx.draw_networkx_nodes(G,pos,node_size=7000, node_color="white")

# edges
nx.draw_networkx_edges(G,pos,
        width=6,alpha=0.5,edge_color='black')


# labels
nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')

nx.draw_networkx_edge_labels(G,pos, 
    {
        (a,b):"x", (b,c):"y", (c,d):"w", (a,d):"z", (a,c):"v", (b,d):"r"
    }
)

plt.axis('off')
plt.savefig("weighted_graph.png") # save as png
plt.show() # display
like image 720
petr Avatar asked Apr 11 '12 11:04

petr


1 Answers

I use version 1.6 of NetworkX, and there I can submit label_pos to draw_networkx_edge_labels(). By default, this is set to 0.5, but using your example and setting it to 0.3, I get the following result: Weighted graph with edge labels shifted

nx.draw_networkx_edge_labels(G,pos, 
    {
        (a,b):"x", (b,c):"y", (c,d):"w", (a,d):"z", (a,c):"v", (b,d):"r"
    },
    label_pos=0.3
)

Here are the details

like image 117
Maehler Avatar answered Oct 28 '22 14:10

Maehler