I'm using NetworkX for the first time and I'm drawing a simple network based on a pandas dataframe.
The nodes are in Nodes_df, which has the ID and corresponding Group, where the group determines what colour the node will be. The Edges_df has the edges which are the ties between ID and ID_2. All of the ids are in Nodes_df.
I can draw the graph, and colour the nodes based on a dictionary which replaces the strings (i.e. "Group1") with a number which is used by the cmap argument.
Colour_df = Edges_df.replace({"Group5": 5,"Group4": 4, "Group3": 3, "Group2": 2, "Group1": 1})
Colour_map = dict(zip(Nodes_df["ID"].astype(float), Colour_df["Group"]))
G = nx.from_pandas_edgelist(df=Edges_df, source="ID", target="ID_2",
create_using=nx.Graph())
values = [Colour_map.get(node) for node in G.nodes()]
nx.draw(G, cmap=plt.get_cmap('Spectral'), node_color=values,
node_size=20)
plt.show()
I'm using matplotlib and I cannot get a legend to appear on the graph. I've tried passing the dictionary to the label argument in nx.draw_networkx_nodes() but I just get KeyError: 5.
I just want a legend that looks like:
[ ] Group1
[ ] Group2
[ ] Group3
[...]
