需要在 python 中更改 networkx 库中节点的形状

need to change shape of the node in networkx library in python

这是一个硬编码示例。 我想要我的节点有不同的形状。我想要圆形方形等。目前我只能为图表添加一种形状。是否可以按照我为节点位置/位置和颜色指定的方式指定不同的形状。

import networkx as nx
import matplotlib.pyplot as plt

G=nx.Graph()

G.add_edges_from([("1", "2" ), ("3", "2"),("4", "2"), ("2", "5"),("5", "6"),("6", "7")])

pos = {"1": [0,1],
       "2": [1,0],
       "3": [0,0],
       "4": [0,-1],
       "5": [2,0],
       "6": [3,0],
       "7": [4,0]
       }
nx.draw(G,pos, node_color= ["#80d189","#de3737","#80d189","#80d189","#ccbfbe","#ccbfbe","#ccbfbe"],node_size = [3000,15000,3000,3000,3000,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","#80d189","#ccbfbe","#ccbfbe","#ccbfbe"]
node_sizes = [3000,15000,3000,3000,3000,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)