Networkx: how get attribute color from the graph

2019-07-26 15:07发布

问题:

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()

回答1:

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.



回答2:

Just your node hasn't attribute color. Your graph has such attribute

UPD:

but if you wanna see the color of nodes you can use

plt_.properties()['facecolor']

with output

array([[ 1., 0., 0., 1.]])

first three elements of this list is color in RGB format