1
votes

I used the answer of this question :

Color a particular node in Networkx and Graphviz

but its not working, this is basically how i am using it :

myGraph.add_node(name , color="blue" , style='filled',fillcolor='blue', shape='square')
nx.draw(myGraph, with_labels=True, font_weight='bold')
plt.show()

but the output graph doesn't have any color at all, what am i doing wrong? it doesn't work with add_edge either, no color at all. i am using python 2.7 ( i cant use 3+)

and i don't want to add colors all at the same time, i need to add colors as i add nodes/edges one at a time.

1

1 Answers

1
votes

The link you pointed if for drawing colored nodes in Graphviz, while you are drawing using networkx. You need to specify a color sequence and provide that value to node_color attribute to nx.draw, something like this:

import matplotlib.pyplot as plt
import networkx as nx

myGraph = nx.path_graph(n=5)

# Add your node. You can add more nodes if you want,
# just remember to specify the color for the new nodes, 
# else they will get the default color
name = "colored_Node"
myGraph.add_node(name,
                 color='green',
                 style='filled',
                 fillcolor='blue',
                 shape='square')

# Get the colored dictionary
colored_dict = nx.get_node_attributes(myGraph, 'color')

# Create a list for all the nodes
default_color = 'blue'
color_seq = [colored_dict.get(node, default_color) for node in myGraph.nodes()]

# Pass the color sequence
nx.draw(myGraph, with_labels=True, font_weight='bold', node_color=color_seq)
plt.show()

Here is a sample graph:
Color a specific node.

References: