Pete Watcharawit
Pete Watcharawit

Reputation: 19

How can I add a color to a particular edge?

I am struggling with how to add color to a specific edge here. Let's say I want to have blue color for the edge from one to two without having to rewrite other edges? also, I would like to know if we can have an arrow pointing from a node to another rather than a straight line for the edge?

import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
class obj(object):
    def __init__(self,N,P):
        self.N = N
        self.P = P 
one   = obj(1,0.5)
two   = obj(2,0.4)
three = obj(3,0.3)
four  = obj(4,0.2)
G.add_node(one.N)
G.add_node(two.N)
G.add_node(three.N)
G.add_node(four.N)

G.add_edge(one.N,two.N)
G.add_edge(two.N,three.N)
G.add_edge(two.N,four.N)
G.add_edge(four.N,one.N)

nx.draw(G)
plt.show()

Upvotes: 0

Views: 4754

Answers (1)

mdml
mdml

Reputation: 22872

You can draw edges with different colors using the edge_color parameter to networkx.draw. Here's an example where you make the first edge (1,2) to red, and make the other edges blue by passing an "edge color tuple" that lists the color of each edge. In this example the first edge is red while the others are blue.

nx.draw(G, pos=pos, edge_color=('r', 'b', 'b', 'b'))

example drawing

If you want to have arrows on the edges, you could use a DiGraph (directed graph). All you'd have to change is:

G = nx.DiGraph()

and then your edges would be directed.

example-drawing-directed

If you wanted the arrows to point in both directions, you'd have to add each edge in each direction and update the tuple of edge colors (since now you have twice as many edges):

# Add edges in each direction
G.add_edge(one.N,two.N)
G.add_edge(two.N,one.N)
G.add_edge(two.N,three.N)
G.add_edge(three.N,two.N)
G.add_edge(two.N,four.N)
G.add_edge(four.N,two.N)
G.add_edge(four.N,one.N)
G.add_edge(one.N, four.N)

# Draw the graph
pos = nx.spring_layout(G)
nx.draw(G, pos=pos, edge_color=('r', 'b', 'r', 'b', 'b', 'b', 'b', 'b'))

example-drawing-directed-both-ways

Upvotes: 1

Related Questions