0 python data-visualization matplotlib networkx
这是一个硬编码的示例。我想要不同形状的节点。我想要圆形、方形等。目前我只能为图表添加一种形状。是否可以按照我为节点位置/位置和颜色指定的方式指定不同的形状。
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
Run Code Online (Sandbox Code Playgroud)
小智 5
该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)
Run Code Online (Sandbox Code Playgroud)