Adding a colormap to a figure without imshow/countour set

Posted on 25 March 2015 in matplotlib

Example: plot a packing using circles, and use the foreground color to show some value for each particle, for example the contact number Z:

The trick to this is to call plt.scatter() to plot a single point outside the axis range. This allows plt.colorbar() to find cmap and norm, which means creating the color bar is now a breeze.

colors = plt.cm.hot_r(np.linspace(0,1,7))
cmap, norm = mpl.colors.from_levels_and_colors(np.arange(-0.5,7,1), colors)

contacts = V_harm.get_contacts(pack)
nC = np.sum(contacts["connmatrix"], axis=0)

plt.figure()
ax = plt.subplot(111, aspect= 'equal')

for i in range(len(pack['particles'])):
    color = cmap(norm([nC[i]]))[0]
    part = pack['particles'][i]

    circ = mpl.pylab.Circle((part['x'], part['y']), radius=part['r'], fc=color)
    plt.gca().add_patch(circ)

plt.axis(xmin=-0.05, xmax=0.05, ymin=-0.05, ymax=0.05)

# Add a single point outside of the axis range with the same cmap and norm
plt.scatter([-100], [-100], c=[0], cmap=cmap, norm=norm)
cb = plt.colorbar()
cb.set_ticks([0,1,2,3,4,5,6])
cb.set_label("Z")