mar*_*rth 3 python graph networkx
所以我有来自networkx示例的代码,但我想弄清楚如何限制半径'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)
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()
Run Code Online (Sandbox Code Playgroud)
你可以使用dict理解,例如
p = {node:length for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
if length < 5}
Run Code Online (Sandbox Code Playgroud)
将dict限制为距离ncenter为<5的节点.
对于Python2.6或更早版本,您可以使用
p = dict((node, length) for node, length in nx.single_source_shortest_path_length(G,ncenter).items()
if length < 5)
Run Code Online (Sandbox Code Playgroud)
你也可以替换
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
Run Code Online (Sandbox Code Playgroud)
单线:
ncenter, _ = min(pos.items(), key = lambda (node, (x,y)): (x-0.5)**2+(y-0.5)**2)
Run Code Online (Sandbox Code Playgroud)
要仅绘制距离ncenter为<5的节点,请定义子图:
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'))
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
1090 次 |
| 最近记录: |