2

In networkx, I found drawing labels of edges is very easy but I how can I draw length or relative distance of edges?

Here is my test code

G = nx.Graph()
G.add_edge(0, 1, length=1)
G.add_edge(0, 2, length=5)
pos = nx.spring_layout(G)
length = nx.get_node_attributes(G, 'length')

What I mean is the plot should show length between nodes since edge has its corresponding length. Here is example

enter image description here

the distance between 0 and 2 looks larger than that between 0 and 1.

GoingMyWay
  • 16,802
  • 32
  • 96
  • 149
  • @usr2564301, thank you I added a draft in the question. – GoingMyWay Jul 22 '18 at 10:44
  • [Possible duplicate](https://stackoverflow.com/questions/20381460/networkx-how-to-show-node-and-edge-attributes-in-a-graph-drawing). – DYZ Jul 22 '18 at 19:48

1 Answers1

1

Your example shows the length of each edge as a text label. That is, the text gives the length of the edge. But since most networks are not embedded in 2D, they cannot be positioned in a 2D picture that gives the right perspective for lengths as assigned to the graphs.

For example, a triangle graph can have lengths 3, 4 and 12. These cannot be realized in a length-scaled version even though it is a valid graph with valid edge lengths.

If you have an embedding of the nodes into the 2D plane (dict of nodes to 2-tuple position pairs) you can use that to draw the network as you like. But NetworkX does not provide a way to find this embedding. There is a recent Pull Request for planarity testing using NetworkX (#3040).

Aric Hagberg has some code that works with planar graphs. Take a look at this thread: https://groups.google.com/forum/#!topic/networkx-discuss/FdhFedwvtrc

dschult
  • 184
  • 7
  • Thank you for your link. If a triangle graph has lengths 3, 4 and 12, then that is an invalid graph. What I want is drawing a map-like graph, just like the map of America, the length of the edge between New York and DC is much shorter than that between LA and DC in the map. However, it seems like there is no such function in Networkx. – GoingMyWay Jul 23 '18 at 00:50
  • What I'm trying to say is that a triangle graph with lengths 3, 4, and 12 IS a valid graph. Almost any graph you specify with lengths for each edge will not be embedded in 2-D. Graphs are typically in very large dimensional space. We can draw them only by projecting onto 2 dimensions. – dschult Jul 23 '18 at 03:29