Code covered by the BSD License  

Highlights from
ColorBrewer: Attractive and Distinctive Colormaps

image thumbnail

ColorBrewer: Attractive and Distinctive Colormaps

by

 

22 Jan 2014 (Updated )

The complete palette of ColorBrewer colormaps. Simple selection by scheme name and map length.

brewermap(N,scheme)
function [map,num,typ] = brewermap(N,scheme)
% The complete selection of ColorBrewer colorschemes (RGB colormaps).
%
% (c) 2014 Stephen Cobeldick
%
% ### Function ###
%
% Returns any RGB colormap from the ColorBrewer colorschemes, especially
% intended for mapping and plots with attractive, distinguishable colors.
%
% Syntax (basic):
%  map = brewermap(N,scheme); % Select colormap length, select any colorscheme.
%  brewermap('demo')          % View a figure showing all ColorBrewer colorschemes.
% [...,num,typ] = brewermap(...); % The current colorscheme's number of nodes and type.
%
% Syntax (preselect colorscheme):
%  old = brewermap(scheme);   % Preselect any colorscheme, return the previous scheme.
%  map = brewermap(N);        % Use preselected scheme, select colormap length.
%  map = brewermap;           % Use preselected scheme, same length as current figure's colormap.
%
% See the ColorBrewer website for further information about each colorscheme,
% colorblind suitability, licensing, and citations: http://colorbrewer.org/
%
% Note: Due to license restrictions, this Mfile is not distributed with the actual
% ColorBrewer data. Please read the Mfile "brewermap_read.m" for instructions.
%
% See also CUBEHELIX RGBPLOT3 RGBPLOT COLORMAP COLORBAR PLOT PLOT3 SURF CONTOURF IMAGE CONTOURCMAP AXES SET JET LBMAP
%
% ### Color Schemes ###
%
% To reverse the colormap sequence prefix the string token with '*'.
%
% Each colorscheme is defined by a set of hand-picked RGB values (nodes).
% If <N> is greater than the requested colorscheme's number of nodes then:
%  - Sequential and Diverging schemes are interpolated to give larger colormaps.
%  - Qualitative schemes throw an error.
% Else:
%  - Exact values from the ColorBrewer sequences are returned for all schemes.
%
% # Diverging #
%
% Scheme|'BrBG'|'PRGn'|'PiYG'|'PuOr'|'RdBu'|'RdGy'|'RdYlBu'|'RdYlGn'|'Spectral'|
% ------|------|------|------|------|------|------|--------|--------|----------|
% Nodes |  15  |  15  |  15  |  15  |  15  |  15  |   15   |   15   |     15   |
%
% # Qualitative #
%
% Scheme|'Accent'|'Dark2'|'Paired'|'Pastel1'|'Pastel2'|'Set1'|'Set2'|'Set3'|
% ------|--------|-------|--------|---------|---------|------|------|------|
% Nodes |    8   |   8   |   12   |    9    |    8    |   9  |   8  |  12  |
%
% # Sequential #
%
% Scheme|'Blues'|'BuGn'|'BuPu'|'GnBu'|'Greens'|'Greys'|'OrRd'|'Oranges'|'PuBu'|
% ------|-------|------|------|------|--------|-------|------|---------|------|
% Nodes |   13  |  13  |  13  |  13  |   13   |   13  |  13  |    13   |  13  |
%
% Scheme|'PuBuGn'|'PuRd'|'Purples'|'RdPu'|'Reds'|'YlGn'|'YlGnBu'|'YlOrBr'|'YlOrRd'|
% ------|--------|------|---------|------|------|------|--------|--------|--------|
% Nodes |   13   |  13  |    13   |  13  |  13  |  13  |   13   |   13   |   13   |
%
% ### Examples ###
%
% % Plot a scheme's RGB values:
% rgbplot(brewermap(13,'Blues'))  % standard
% rgbplot(brewermap(13,'*Blues')) % reversed
%
% % View information about a colorscheme:
% [~,num,typ] = brewermap(0,'Paired')
%  num = 12
%  typ = 'Qualitative'
%
% % Multiline plot using matrices:
% N = 6;
% axes('ColorOrder',brewermap(N,'Pastel2'),'NextPlot','replacechildren')
% X = linspace(0,pi*3,1000);
% Y = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X.', 1:N);
% plot(X,Y, 'linewidth',4)
%
% % Multiline plot in a loop:
% N = 6;
% set(0,'DefaultAxesColorOrder',brewermap(8,'Accent'))
% X = linspace(0,pi*3,1000);
% Y = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X.', 1:N);
% for n = 1:N
%     plot(X(:),Y(:,n), 'linewidth',4);
%     hold all
% end
%
% % New colors for the "colormap" example:
% load spine
% image(X)
% colormap(brewermap([],'*YlGnBu'))
%
% % New colors for the "surf" example:
% [X,Y,Z] = peaks(30);
% surfc(X,Y,Z)
% colormap(brewermap([],'RdYlGn'))
% axis([-3,3,-3,3,-10,5])
%
% % New colors for the "contourcmap" example:
% brewermap('*PuOr'); % preselect the colorscheme.
% load topo
% load coast
% figure
% worldmap(topo, topolegend)
% contourfm(topo, topolegend);
% contourcmap('brewermap', 'Colorbar','on', 'Location','horizontal',...
%     'TitleString','Contour Intervals in Meters');
% plotm(lat, long, 'k')
%
% ### Input & Output Arguments ###
%
% Inputs (*=default):
%  N   = NumericScalar, N>=0, an integer to define the colormap length.
%      = *[], use the length of the current figure's colormap (see "colormap").
%      = StringToken, to preselect this ColorBrewer scheme for later use.
%      = 'demo', create a figure showing all of the ColorBrewer schemes.
%  scheme = StringToken, a ColorBrewer scheme to select the colorscheme.
%         = *none, use the preselected colorscheme (must be set previously!).
%
% Outputs:
%  map = NumericMatrix, size Nx3, a colormap of RGB values between 0 and 1.
%  num = NumericScalar, the number of nodes defining the ColorBrewer scheme.
%  typ = String, the colorscheme type: 'Diverging'/'Qualitative'/'Sequential'.
%
% [map,num,typ] = brewermap(*N,*scheme)

persistent dcs
%
if nargin==0
    % Use the current figure's colormap length, and the preselected colorscheme.
    assert(~isempty(dcs),'You need to preselect a colorscheme before trying this!')
    [map,num,typ] = cbSample([],dcs);
elseif nargin==2
    % Use the provided colormap length and the provided colorscheme.
    assert(isnumeric(N),'First argument must be a numeric scalar, or empty.')
    assert(ischar(scheme)&&isrow(scheme),'Second argument must be a string.')
    [map,num,typ] = cbSample(N,scheme);
elseif isnumeric(N)
    % Use the provided colormap length, and the preselected colorscheme.
    assert(~isempty(dcs),'You need to preselect a colorscheme before trying this!')
    [map,num,typ] = cbSample(N,dcs);
else% String
    assert(ischar(N)&&isrow(N),'First argument must be a string or numeric.')
    switch N
        case 'demo'
            % Plot all colorschemes in a figure.
            cbDemoFig
        case 'list'
            % Return a list of all available colorschemes.
            map = cbListTok;
            [num,typ] = cellfun(@cbSelect,map,'UniformOutput',false);
            num = cat(1,num{:});
        otherwise
            % Store the preselected colorscheme token.
            map = dcs;
            [num,typ] = cbSelect(N(1+strncmp('*',N,1):end));
            dcs = N;
    end
end
%
end
%----------------------------------------------------------------------END:brewermap
function [map,num,typ] = cbSample(N,tok)
% Pick a colorscheme, downsample/interpolate to the requested colormap length.
%
if isempty(N)
    N = size(get(gcf,'colormap'),1);
else
    assert(isscalar(N)&&isreal(N),'First argument must be a real numeric scalar, or empty.')
end
%
if strncmp('*',tok,1);
    vec = N:-1:1;
    tok = tok(2:end);
else
    vec = 1:+1:N;
end
%
[num,typ,rgb] = cbSelect(tok);
%
if strncmpi(typ,'Q',1)
    % Exact (Qualitative).
    assert(N<=num,'Colorscheme "%s" maximum colormap length: %d. Requested: %d.',tok,num,N)
    map = rgb(vec,:);
elseif N<num
    % Downsample (Diverging / Sequential).
    map = rgb(cbIndex(N,num,typ,vec),:);
elseif N>num
    % Interpolate (Diverging / Sequential).
    xi = (vec-1).' / (N-1);
    map = interp1q((1:num).', rgb, num*xi + xi(end:-1:1));
    %map = interp1((1:num).', rgb, num*xi + xi(end:-1:1), 'pchip');
else
    % Exact (Diverging / Sequential).
    map = rgb(vec,:);
end
%
end
%----------------------------------------------------------------------END:cbSample
function cbDemoFig
% Creates a figure showing all of the ColorBrewer colorschemes.
%
persistent cbh axh
%
seq = cbListTok;
xmx = max(cellfun(@cbSelect,seq));
ymx = numel(seq);
%
if ishghandle(cbh)
    figure(cbh);
    delete(axh);
else
    cbh = figure('HandleVisibility','callback', 'NumberTitle','off', 'Name',[mfilename,' Demo'],'Color','white');
end
axh = axes('Parent',cbh, 'XTick',0:xmx, 'YTick',0.5:ymx, 'YTickLabel',seq, 'YDir','reverse','Color','none');
title(axh,['ColorBrewer Color Schemes (',mfilename,'.m)'], 'Interpreter','none')
xlabel(axh,'Scheme Nodes')
ylabel(axh,'Scheme Name')
%
for y = 1:ymx
    [num,typ,rgb] = cbSelect(seq{y});
    for x = 1:num
        patch([x-1,x-1,x,x],[y-1,y,y,y-1],1, 'FaceColor',rgb(x,:), 'Parent',axh)
    end
    text(xmx+0.1,y-0.5,typ, 'Parent',axh)
end
%
end
%----------------------------------------------------------------------END:cbDemoFig
function idx = cbIndex(N,num,typ,vec)
% Ensure exactly the same colors as in the online ColorBrewer schemes.
%
if strncmp('D',typ,1) && 3<=N && N<=11
    switch N
        case 3
            idx = [5,8,11];
        case 4
            idx = [3,6,10,13];
        case 5
            idx = [3,6,8,10,13];
        case 6
            idx = [2,5,7,9,11,14];
        case 7
            idx = [2,5,7,8,9,11,14];
        case 8
            idx = [2,4,6,7,9,10,12,14];
        case 9
            idx = [2,4,6,7,8,9,10,12,14];
        case 10
            idx = [1,2,4,6,7,9,10,12,14,15];
        case 11
            idx = [1,2,4,6,7,8,9,10,12,14,15];
    end
    idx = idx(vec);
elseif strncmp('S',typ,1) && 3<=N && N<=9
    switch N
        case 3
            idx = [3,6,9];
        case 4
            idx = [2,5,7,10];
        case 5
            idx = [2,5,7,9,11];
        case 6
            idx = [2,4,6,7,9,11];
        case 7
            idx = [2,4,6,7,8,10,12];
        case 8
            idx = [1,3,4,6,7,8,10,12];
        case 9
            idx = [1,3,4,6,7,8,10,11,13];
    end
    idx = idx(vec);
else
    % Evenly spaced downsampling:
    idx = round((1+num) * vec / (1+N));
end
%
end
%----------------------------------------------------------------------END:cbIndex
function seq = cbListTok
% Return a list of all colorschemes, sorted by type and scheme name.
%
YYYYY !!! This line must be replaced !!! Please see the Mfile <brewermap_read.m> !!!
%
end
%----------------------------------------------------------------------END:cbListTok
function [num,typ,rgb] = cbSelect(tok)
% Return the length, type and RGB values of any colorscheme.
%
switch lower(tok) % ColorName
XXXXX !!! This line must be replaced !!! Please see the Mfile <brewermap_read.m> !!!
    otherwise
        error('Colorscheme "%s" is not supported. Check the token tables.', tok)
end
num = size(rgb,1);
rgb = rgb./255;
%
end
%----------------------------------------------------------------------END:cbSelect

Contact us