如何解决需要在python的networkx库中更改节点的形状
这里有一个硬编码的示例。 我希望节点具有不同的形状。我想要圆圈正方形等。目前,我只能为图表添加一个形状。是否可以按照我为节点位置/位置和颜色指定的方式指定不同的形状。
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_edges_from([("1","2" ),("3","2"),("4",("2","5"),("5","6"),("6","7")])
pos = {"1": [0,1],"2": [1,0],"3": [0,"4": [0,-1],"5": [2,"6": [3,"7": [4,0]
}
nx.draw(G,pos,node_color= ["#80d189","#de3737","#80d189","#ccbfbe","#ccbfbe"],node_size = [3000,15000,3000,3000],with_labels = True)
plt.savefig("simple_path.png") # save as png
plt.show() # display
解决方法
node_shape
参数接受一个指定形状的字符,因此,如果要使用多个形状,可以在for循环中分别绘制它们。 nx.draw_networkx_*
函数对于这种类型的操作更加灵活。
# Add plotting data as node attributes
node_colors= ["#80d189","#de3737","#80d189","#ccbfbe","#ccbfbe"]
node_sizes = [3000,15000,3000,3000]
# odd nodes as squares even as circles
node_shapes = ['s' if i % 2 == 0 else 'o' for i in range(len(G.nodes()))]
for i,node in enumerate(G.nodes()):
G.nodes[node]['color'] = node_colors[i]
G.nodes[node]['size'] = node_sizes[i]
G.nodes[node]['shape'] = node_shapes[i]
#%% Draw Graph
nx.draw_networkx_edges(G,pos) # draw edges
nx.draw_networkx_labels(G,pos) # draw node labels
# Draw the nodes for each shape with the shape specified
for shape in set(node_shapes):
# the nodes with the desired shapes
node_list = [node for node in G.nodes() if G.nodes[node]['shape'] == shape]
nx.draw_networkx_nodes(G,pos,nodelist = node_list,node_size = [G.nodes[node]['size'] for node in node_list],node_color= [G.nodes[node]['color'] for node in node_list],node_shape = shape)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。