Networkx:如何从图中获取属性颜色

问题描述:

我有一个图,我需要获取节点的颜色. 我尝试使用

I have graph and I need to get color of nodes. I try to use

color = nx.get_node_attributes(G, 'color')

但是它返回空字典. 我做错了什么? 图是使用

But it returns empty dictionary. What I do wrong? Graph was generated with

G = nx.erdos_renyi_graph(100, 0.05)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, G.nodes(), node_size=20, node_color='b')
nx.draw_networkx_edges(G,pos, alpha=0.3)
plt.show()

您从未为节点分配颜色.在用于绘制图形以使其可视化的命令中,您碰巧告诉它使用蓝色.但这与为节点本身分配颜色不同.同样,如果您已为节点分配了一个属性,则说它们的颜色为红色,这不会影响绘图中使用的颜色.

You never assigned a color to the nodes. In your command to plot the graph so that it could be visualized, you happened to tell it to use blue. But that is not the same as assigning a color to the nodes themselves. Similarly, if you had assigned an attribute to the nodes, say that their color is red, that won't affect the color used in the plot.

您可以在此处中看到有关添加节点属性的更多信息.

You can see more about adding node attributes here.