Reputation: 343
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)
Is there a way to randomly change colours of different sets of nodes and edges between them?
Upvotes: 3
Views: 3294
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
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()
Upvotes: 4