21

I am writing a program to plot a graph from a distance matrix. It is working fine. Now I want a certain node and a certain edge to be of a particular color of my choice. How do I do that?

The program is in Python and uses Networkx and Graphviz

import networkx as nx
import numpy as np
import pickle
from random import randint

p_file = open('pickles/distance')
Dist = pickle.load(p_file)
p_file.close()
p_file = open('pickles/names')
Names = pickle.load(p_file)
p_file.close()

dt = [('len', float)]
A = np.array(Dist)*5
A = A.view(dt)

G = nx.from_numpy_matrix(A)
G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),Names)))    

G = nx.to_agraph(G)
G.node_attr.update(ndcolor="red", node="DC", style="filled")
G.edge_attr.update(color="none")
G.draw('P1.png', format='png', prog='neato')
Anirudh
  • 854
  • 1
  • 11
  • 32

1 Answers1

31

Since you are using Graphviz to do the drawing you need to use the attributes that Graphviz understands. See https://graphviz.gitlab.io/_pages/doc/info/attrs.html

import networkx as nx
from networkx.drawing.nx_agraph import to_agraph

G = nx.Graph()

G.add_node(1,color='red',style='filled',fillcolor='blue',shape='square')
G.add_node(2,color='blue',style='filled')
G.add_edge(1,2,color='green')
G.nodes[2]['shape']='circle'
G.nodes[2]['fillcolor']='red'

A = to_agraph(G)
A.layout()
A.draw('color.png')
print(A.to_string())

Gives

strict graph {
    graph [bb="0,0,107.21,46.639"];
    node [label="\N"];
    1    [color=red,
        fillcolor=blue,
        height=0.5,
        pos="18,28.639",
        shape=square,
        style=filled,
        width=0.5];
    2    [color=blue,
        fillcolor=red,
        height=0.5,
        pos="89.21,18",
        shape=circle,
        style=filled,
        width=0.5];
    1 -- 2   [color=green,
        pos="36.338,25.899 47.053,24.298 60.519,22.286 71.18,20.694"];
}

enter image description here

Aric
  • 24,511
  • 5
  • 78
  • 77
  • 1
    As you can see in my code, I am adding nodes and edges from the distance matrix. The method you have mentioned cannot be applied in this case. Do you know any other method? – Anirudh Dec 11 '12 at 15:59
  • 1
    You can add the attributes after you create the graph G. Use G.node[nodename]['color']='red', etc. – Aric Dec 11 '12 at 17:59
  • 1
    Oh it worked! Thank you Aric. Can you pls add this to the answer so that it'll help others too. – Anirudh Dec 11 '12 at 19:56
  • Watch out, your first link seems dead ;) – iago-lito Jun 26 '19 at 10:44
  • 1
    Does this code work in 2019? I get AttributeError: 'module' object has no attribute 'to_agraph'. See https://stackoverflow.com/questions/35279733/what-could-cause-networkx-pygraphviz-to-work-fine-alone-but-not-together How to make the above work? – PizzaBeer Nov 10 '19 at 22:42