栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

修复NetworkX弹簧图中的节点子集的位置

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

修复NetworkX弹簧图中的节点子集的位置

要创建图并设置一些位置:

import networkx as nxG=nx.Graph()G.add_edges_from([(1,2),(2,3),(3,1),(1,4)]) #define Gfixed_positions = {1:(0,0),2:(-1,2)}#dict with two of the positions setfixed_nodes = fixed_positions.keys()pos = nx.spring_layout(G,pos=fixed_positions, fixed = fixed_nodes)nx.draw_networkx(G,pos)

您的问题似乎是在设置固定节点的位置之前先计算了所有节点的位置。

pos = nx.spring_layout(G_pc,fixed=fixed_nodes)
设置
pos[p]
固定节点后移至,然后将其更改为
pos= nx.spring_layout(G_pc,pos=pos,fixed=fixed_nodes)

dict

pos
存储每个节点的坐标。您应该快速浏览一下文档。特别是,

pos :dict或None可选(默认= None)。节点的初始位置作为字典,节点作为键,值作为列表或元组。如果为None,则使用随机初始位置。

固定 :列表或无可选(默认=无)。固定在初始位置的节点。列表或无可选(默认=无)

您是在告诉它将那些节点固定在其初始位置,但是您没有告诉他们该初始位置应该是什么。因此,我相信它会对该初始位置进行随机猜测,并保持固定不变。但是,当我对此进行测试时,似乎遇到了错误。看来,如果我告诉(我的版本)networkx将节点保持

[1,2]
为固定,但我不告诉它们它们的位置是什么,则会出现错误(此答案的底部)。所以我很惊讶您的代码正在运行。


对于使用列表推导的代码的其他一些改进:

def get_coordinates_in_circle(n):    thetas = [2*np.pi*(float(i)/n) for i in range(n)]    returnlist = [(np.cos(theta),np.sin(theta)) for theta in thetas]    return return_listG_pc = nx.Graph()G_pc.add_edges_from(edges_2212)circular_positions = get_coordinates_in_circle(len(dps_2211))#it's not clear to me why you don't define circular_positions after#fixed_nodes with len(fixed_nodes) so that they are guaranteed to #be evenly spaced.fixed_nodes = [n for n in G_pc.nodes() if n in production_companies]pos = {}for i,p in enumerate(fixed_nodes):    pos[p] = circular_positions[i]colors = get_node_colors(G_pc, "gender")pos = nx.spring_layout(G_pc,pos=pos, fixed=fixed_nodes)nx.draw_networkx_nodes(G_pc, pos, cmap=plt.get_cmap('jet'), node_color=colors, node_size=50, alpha=0.5)nx.draw_networkx_edges(G_pc,pos, alpha=0.01)plt.show()

这是我看到的错误:

import networkx as nxG=nx.Graph()G.add_edge(1,2)pos = nx.spring_layout(G, fixed=[1,2])---------------------------------------------------------------------------UnboundLocalError   Traceback (most recent call last)<ipython-input-4-e9586af20cc2> in <module>()----> 1 pos = nx.spring_layout(G, fixed=[1,2]).../networkx/drawing/layout.pyc in fruchterman_reingold_layout(G, dim, k, pos, fixed, iterations, weight, scale)    253 # We must adjust k by domain size for layouts that are not near 1x1    254 nnodes,_ = A.shape--> 255 k=dom_size/np.sqrt(nnodes)    256         pos=_fruchterman_reingold(A,dim,k,pos_arr,fixed,iterations)    257     if fixed is None:UnboundLocalError: local variable 'dom_size' referenced before assignment


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611186.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号