2

I am performing clustering on relational graphs, and am currently using networkx to visualize the result:

G = nx.from_numpy_matrix(X)
layout = nx.fruchterman_reingold_layout(G)
nx.draw_networkx(G, pos=layout, with_labels=True, node_color=predict, cmap=plt.cm.coolwarm, vmin=0, vmax=1)

enter image description here

Is it possible to get a colorbar? Simply using plt.colorbar() gives the error:

RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

And there aren't any options in the documentation. I am also open to use another package for visualization as long as it is compatible with Python 3.

Toke Faurby
  • 5,788
  • 9
  • 41
  • 62
  • It's not apparent how you create this graph from the question. What the error tells you is that you need to supply an argument to the colorbar function. You may use a [`matplotlib.cm.ScalarMappable`](https://matplotlib.org/api/cm_api.html#matplotlib.cm.ScalarMappable) which uses the same vmin, vmax and colormap as the networks graph and supply it as argument to the colorbar function. – ImportanceOfBeingErnest Mar 30 '18 at 10:21
  • Updated the question. I am not sure how to use `matplotlib.cm.ScalarMappable` simply supplying it to `plt.colorbar()` didn't work. Any pointers? – Toke Faurby Mar 30 '18 at 10:34
  • Well, according to the usual approach for Stackoverflow questions and answers, you may provide a [mcve] of the issue that I can run, modify and test, such that I can subsequently provide you with an answer, showing the exact code to use here. – ImportanceOfBeingErnest Mar 30 '18 at 10:36
  • @TokeFaurby, can you provide values for `predict`, so we could reproduce it ? – MaxU - stand with Ukraine Mar 30 '18 at 15:24

1 Answers1

8

Here is a demo based on Karate Club graph:

import pandas as pd
import networkx as nx    
import matplotlib.pyplot as plt

G = nx.karate_club_graph()

df = (pd.DataFrame(list(G.degree), columns=['node','degree'])
        .set_index('node'))
df['club'] = pd.Series({node:data['club']
                        for node,data in G.nodes(data=True)})
df['color'] = df.groupby('club')['degree'].transform(lambda c: c/c.max())
df.loc[df['club']=='Officer', 'color'] *= -1

layout = nx.fruchterman_reingold_layout(G)
vmin = df['color'].min()
vmax = df['color'].max()
cmap = plt.cm.coolwarm

nx.draw_networkx(G, pos=layout, with_labels=True, node_color=df['color'],
                 cmap=cmap, vmin=vmin, vmax=vmax)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax))
sm.set_array([])
cbar = plt.colorbar(sm)

Result:

enter image description here

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419