efedoganay
efedoganay

Reputation: 133

Networkx node positioning in a complete graph

I want to draw an undirected, weighted, and complete graph with networkx library. My aim is to draw this graph in a way that edge weights represent the distance between nodes.

For example, consider the set of nodes and edges below:

A, B, weight = 5.0

A, C, weight = 50.0

B, C, weight = 0.5

In this case, the distance between A-C is the smallest and B-C is the largest.

I was able to draw this with (after adding edges and nodes to G)

nx.draw(G, pos=None)

but, as the number of nodes gets bigger (above 6), inconsistencies occur. What I mean by this is that some nodes get closer although the weight of the edge connecting them is very low.

I assume some of the node positions don't get updated after some point, but I am not sure.

Any suggestions ?

Upvotes: 1

Views: 1598

Answers (1)

warped
warped

Reputation: 9482

You can generate the layout of the graph, and compute distances based on the layout. Then, you can assign 1/distance as edge weight. Close edges will have stronger connections, edges that are further away will have fainter connections.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.complete_graph(15)

# generate positions
pos = nx.spring_layout(G)

# calculate distances and store as weights
from scipy.spatial.distance import euclidean
edge_updates = {}
edge_widths = []
for (a,b,_) in G.edges(data=True): 
    distance = euclidean(pos[a], pos[b])
    edge_updates[a,b] = {'distance': distance}
    edge_widths.append(1/distance)
nx.set_edge_attributes(G, edge_updates)



nx.draw_networkx_nodes(G, pos=pos)
a = nx.draw_networkx_edges(G, pos=pos, edge_cmap=plt.cm.magma, width=edge_widths)

enter image description here

Upvotes: 1

Related Questions