Networkx Random Geometric Graph limit nodes within radius r
graph, networkx, python
Solution
You could use a dict comprehension such as
p = {node:length for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
if length < 5}
to limit the dict to those nodes whose distance from `ncenter` is < 5.
For Python2.6 or older, you could use
p = dict((node, length) for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
if length < 5)
You could also replace
dmin =1
ncenter =0
for n in pos:
x,y = pos[n]
d = (x-0.5)**2+(y-0.5)**2
if d<dmin:
ncenter = n
dmin = d
with a one-liner:
ncenter, _ = min(pos.items(), key = lambda (node, (x,y)): (x-0.5)**2+(y-0.5)**2)
To draw only those nodes whose distance from `ncenter` is < 5, define the subgraph:
H = G.subgraph(p.keys())
nx.draw_networkx_edges(H, pos, alpha = 0.4)
nx.draw_networkx_nodes(H, pos, node_size = 80, node_color = node_color,
cmap = plt.get_cmap('Reds_r'))
import networkx as nx
import matplotlib.pyplot as plt
G = nx.random_geometric_graph(1000, 0.1)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, 'pos')
# find node near center (0.5,0.5)
ncenter, _ = min(pos.items(), key = lambda (node, (x, y)): (x-0.5)**2+(y-0.5)**2)
# color by path length from node near center
p = {node:length
for node, length in nx.single_source_shortest_path_length(G, ncenter).items()
if length < 5}
plt.figure(figsize = (8, 8))
node_color = p.values()
H = G.subgraph(p.keys())
nx.draw_networkx_edges(H, pos, alpha = 0.4)
nx.draw_networkx_nodes(H, pos, node_size = 80, node_color = node_color,
cmap = plt.get_cmap('Reds_r'))
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis('off')
plt.savefig('random_geometric_graph.png')
plt.show()
Problem
So I have this code from the networkx example, but I'm trying to figure out how to limit node within a radius 'r' in order to graph a random geometric graph within the bounds of a circle. I know how I would do it logic-wise, but I'm a bit confused how everything works and have been trying to figure it out on my own with no solution so far. Thanks for the help! ``` import networkx as nx import matplotlib.pyplot as plt G = nx.random_geometric_graph(1000,0.1) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G,'pos') # find node near center (0.5,0.5) dmin =1 ncenter =0 for n in pos: x,y = pos[n] d = (x-0.5)**2+(y-0.5)**2 if d<dmin: ncenter = n dmin = d # color by path length from node near center p = nx.single_source_shortest_path_length(G,ncenter) plt.figure(figsize=(8,8)) #node_color=p.values() nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4) nx.draw_networkx_nodes(G,pos,nodelist=p.keys(), node_size=80, node_color='#0F1C95', cmap=plt.cm.Reds_r) plt.xlim(-0.05,1.05) plt.ylim(-0.05,1.05) plt.axis('off') plt.savefig('random_geometric_graph.png') plt.show() ```