ampron
ampron

Reputation: 3666

Matplotlib: How to add two custom colorbars to an image map

The setup... I have a set of paired values (z,w) that are mapped over 2D space (i.e. f(x,y) = (z,w)) that I'm making an image map from. My preferred way of doing this is where the rgb color at each point is given as: (r,g,b) = (z'w', z'(1-w'), z'), z' and w' being normalized to be between 0 and 1 (for colormapping purposes). In this way the z value effectively determines the lightness of the point and the w value determines the red-blue hue.

Here's the issue... I can make this image map but the colorbar is a rainbow colormap (somehow), which is not very helpful. Instead I need two independent, custom colorbars. What I would like is to have a vertical colorbar to the right that is black-white and scaled to the range of z, and a horizontal colorbar on the bottom that is blue-red and scaled to the range of w.

Does anyone know how to do this?

Upvotes: 2

Views: 2278

Answers (1)

ampron
ampron

Reputation: 3666

As imsc pointed out in a comment to my question, the answer lies in the matplotlib example he linked to. Here is the code that I'm using, following the linked example, that solves the situation in my question specifically:

import matplotlib as mpl

ax_cb1 = fig.add_axes((0.85, 0.125, 0.03, 0.75))
BW_cdict = {
    'red':    ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0)),
     'green': ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0)),
     'blue': ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0))
    }
black_white = mpl.colors.LinearSegmentedColormap('BlackWhite', BW_cdict)
norm = mpl.colors.Normalize(vmin=z_min, vmax=z_max)
cb1 = mpl.colorbar.ColorbarBase(
    ax_cb1, cmap=black_white, norm=norm, orientation='vertical'
)

ax_cb2 = fig.add_axes((0.125, 0.95, 0.75, 0.03))
BR_cdict = {
    'red':    ((0.0, 0.0, 0.0),
               (1.0, 1.0, 1.0)),
     'green': ((0.0, 0.0, 0.0),
               (1.0, 0.0, 0.0)),
     'blue':  ((0.0, 1.0, 1.0),
               (1.0, 0.0, 0.0))
    }
blue_red = mpl.colors.LinearSegmentedColormap('BlueRed', BR_cdict)
norm = mpl.colors.Normalize(vmin=w_min, vmax=w_max)
cb2 = mpl.colorbar.ColorbarBase(
    ax_cb2, cmap=blue_red, norm=norm, orientation='horizontal'
)

Upvotes: 2

Related Questions