## Re: [Matplotlib-users] Making a data-driven colormap

 Re: [Matplotlib-users] Making a data-driven colormap From: Friedrich Romstedt - 2010-03-30 13:52:18 Attachments: cbar.py cbar.png ```2010/3/30 Ariel Rokem : > I ended up with the code below, using Chloe's previously posted > 'subcolormap' and, in order to make the colorbar nicely attached to the main > imshow plot, I use make_axes_locatable in order to generate the colorbar > axes. I tried it out with a couple of use-cases and it seems to do what it > is supposed to, (with ticks only for the edges of the range of the data and > 0, if that is within that range), but I am not entirely sure. Do you think > it works? I think even Chloe would agree that you should avoid the subcolormap() if you can. I tried to create an as minimalistic as possible but working self-contained example, please find the code also attached as .py file: from matplotlib import pyplot as plt import matplotlib as mpl from mpl_toolkits.axes_grid import make_axes_locatable import numpy as np fig = plt.figure() ax_im = fig.add_subplot(1, 1, 1) divider = make_axes_locatable(ax_im) ax_cb = divider.new_vertical(size = '20%', pad = 0.2, pack_start = True) fig.add_axes(ax_cb) x = np.linspace(-5, 5, 101) y = x Z = np.sin(x*y[:,None]).clip(-1,1-0.1) # Leave out if you want: Z += 2 min_val = Z.min() max_val = Z.max() bound = max(np.abs(Z.max()), np.abs(Z.min())) patch = ax_im.imshow(Z, origin = 'upper', interpolation = 'nearest', vmin = -bound, vmax = bound) cb = fig.colorbar(patch, cax = ax_cb, orientation = 'horizontal', norm = patch.norm, boundaries = np.linspace(-bound, bound, 256), ticks = [min_val, 0, max_val], format = '%.2f') plt.show() Friedrich ```