Skip to content

Instantly share code, notes, and snippets.

@AruniRC
Created July 30, 2019 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AruniRC/2c53fe7680eeb578593ec816bbfb1653 to your computer and use it in GitHub Desktop.
Save AruniRC/2c53fe7680eeb578593ec816bbfb1653 to your computer and use it in GitHub Desktop.
Adding edge thickness and node colors in NetworkX graph plotting
# saliency
sal = cluster_saliency[cluster_label] # [ (grad-norm, grad-max)
grad_max = sal[1] / max(sal[1])
feat_vertices = features[cluster_ids, :]
adj_mat = get_adjmat(feat_vertices, is_norm_adj=False)
adj_mat_normed = get_adjmat(feat_vertices, is_norm_adj=True)
# create networkx graph from adjacency matrix
g = nx.from_numpy_matrix(adj_mat_normed)
affinities = {}
for edge in g.edges():
affinities[edge] = adj_mat_normed[edge[0], edge[1]]
nx.set_edge_attributes(g, affinities, 'my_weight')
pos = nx.spring_layout(g, weight = 'my_weight')
edge_wts = [15.0 * adj_mat_normed[edge[0], edge[1]] for edge in g.edges()]
node_szs = [100*grad_max[node] for node in g.nodes()] # proportional to "saliency"
# node_szs = [5.0 * adj_mat[node].sum() for node in g.nodes()]
n_colors = [grad_max[node] for node in g.nodes()] # node color also proportional to saliency
plt.figure()
sc = nx.draw_networkx_nodes(G=g, pos = pos, node_list = g.nodes(), alpha=0.9,
node_size = node_szs, node_color=n_colors, cmap='viridis')
nx.draw_networkx_edges(G = g, pos = pos, edge_color='k', alpha=0.6, width=edge_wts)
sc.set_norm(mcolors.LogNorm()) # log-scale colormap for better visualization and contrast
plt.colorbar(sc)
plt.savefig(osp.join(dist_cache, 'cluster_%d.png' % cluster_label))
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment