t1maccapp
t1maccapp

Reputation: 343

How to change colours of nodes and edges of bipartite graph in networkX?

I use this piece of code to draw a bipartite graph using networkX:

import networkx as nx

G = bipartite.from_biadjacency_matrix(a_matrix, create_using=None, edge_attribute='weight')
X, Y = bipartite.sets(G)
pos = dict()
pos.update((n, (0, i*10)) for i, n in enumerate(X))
pos.update((n, (0.5, i*10)) for i, n in enumerate(Y))
nx.draw(G, pos=pos)

enter image description here

Is there a way to randomly change colours of different sets of nodes and edges between them?

Upvotes: 3

Views: 3294

Answers (2)

mfessenden
mfessenden

Reputation: 608

You could use subgraphs to color connected nodes:

    C = nx.connected_component_subgraphs(G)
    for g in C:
         node_colors = [random.random()] * nx.number_of_nodes(g)
         nx.draw(g, pos, node_size=40, node_color=node_colors, vmin=0.0, vmax=1.0, with_labels=False )

Upvotes: 1

unutbu
unutbu

Reputation: 879083

Generate some random numbers:

edge_color=np.random.random(num_edges)
node_color=np.random.random(num_nodes)

and set the edge color map:

edge_cmap=plt.get_cmap('Blues')

and node color map:

cmap=plt.get_cmap('Reds')

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms import bipartite
import scipy.sparse as sparse

a_matrix = sparse.rand(10, 10, format='coo', density=0.8)

G = bipartite.from_biadjacency_matrix(a_matrix, create_using=None, 
                                         edge_attribute='weight')
X, Y = bipartite.sets(G)
pos = dict()
pos.update((n, (0, i*10)) for i, n in enumerate(X))
pos.update((n, (0.5, i*10)) for i, n in enumerate(Y))
num_edges = G.number_of_edges()
num_nodes = G.number_of_nodes()
nx.draw(G, pos=pos, with_labels=True,
        edge_color=np.random.random(num_edges), 
        edge_cmap=plt.get_cmap('Blues'), 
        node_color=np.random.random(num_nodes),
        cmap=plt.get_cmap('Reds'))
plt.show()

enter image description here

Upvotes: 4

Related Questions