'networkx, is their a way to use a dictionary as color_map for node_color?
My aim is to change individualize the color of each node in my dictionary.
My code so far is:
import matplotlib.pyplot as plt
import networkx as nx
def view_graph(graph, node_labels, edge_labels):
'''
Plots the graph
'''
pos = nx.spring_layout(graph)
nx.draw(graph, pos, node_color=color_map)
nx.draw_networkx_labels(graph, pos, labels=node_labels)
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels)
plt.axis('off')
plt.show()
index_to_name = {1: "Paul", 2: "Magda", 3: "Paul", 4: "Anna", 5: "Marie", 6: "John", 7: "Mark"}
color_map2 = {1: "blue", 2: "green", 3: "blue", 4: "lightgreen", 5: "lightgreen", 6: "lightblue", 7: "lightblue"}
color_map = ["blue", "green", "blue", "lightgreen", "lightgreen", "lightblue", "lightblue"]
relation = {}
relation[(1, 4)] = "dad"
relation[(2, 4)] = "mom"
relation[(1, 5)] = "dad"
relation[(2, 5)] = "mom"
relation[(3, 6)] = "dad"
relation[(4, 6)] = "mom"
relation[(3, 7)] = "dad"
relation[(4, 7)] = "mom"
g = nx.from_edgelist(relation, nx.DiGraph())
view_graph(g, index_to_name, relation)
My problem is, I dont want to use color_map as parameter, cause its a list and so it doesn't give me as much control to the nodes itself. My aim is to use the dictionary color_map2 to have a unique relationship between the color and the node itself.
Is their a way to do that?
Solution 1:[1]
As you have noted, parameter specification via dictionaries (rather than lists) is not natively supported in networkx. If you are open to using other libraries, I wrote and maintain netgraph, which is library just for network visualisation.
The project started out as a fork from networkx drawing utilities, so most of the parameters are called the same. However, in netgraph, nearly all parameters can be specified via dictionaries (instead of lists). Netgraph supports plotting of networkx Graph objects, so the two packages work together quite seamlessly.
import matplotlib.pyplot as plt
import networkx as nx
from netgraph import Graph # pip install netgraph
node_labels = {1: "Paul", 2: "Magda", 3: "Paul", 4: "Anna", 5: "Marie", 6: "John", 7: "Mark"}
node_color = {1: "blue", 2: "green", 3: "blue", 4: "lightgreen", 5: "lightgreen", 6: "lightblue", 7: "lightblue"}
relation = {}
relation[(1, 4)] = "dad"
relation[(2, 4)] = "mom"
relation[(1, 5)] = "dad"
relation[(2, 5)] = "mom"
relation[(3, 6)] = "dad"
relation[(4, 6)] = "mom"
relation[(3, 7)] = "dad"
relation[(4, 7)] = "mom"
g = nx.from_edgelist(relation, nx.DiGraph())
Graph(g, node_labels=node_labels, edge_labels=relation,
node_color=node_color, node_edge_color=node_color, arrows=True)
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul Brodersen |

