Skip to content

Instantly share code, notes, and snippets.

@Jwink3101
Created October 12, 2017 14:45
Show Gist options
  • Save Jwink3101/cb2bf18a1a9ad010648e1ffbf0221209 to your computer and use it in GitHub Desktop.
Save Jwink3101/cb2bf18a1a9ad010648e1ffbf0221209 to your computer and use it in GitHub Desktop.
Plot a palette in Matlab
function palette(cmap,varargin)
%% palette - Plot the color palette for a given map on x,y in [0,1]
% in the current window/axis
% Inputs:
% cmap - N x 3 array of colors --OR-- a cell array of 1x3 colors
% Options/Flags (note the `-` on flags)
% -no-label - If specified, will *never* label. Otherwise, will label
% for N<=10
% -vert - Plot vertically
%%%%%%%%%%%%%%%%%%%%%%
%% Parse variables
vert = false;
no_label = false;
% Parse
iv = 1;
while iv <= length(varargin)
param = varargin{iv};
% Replace `-` with `_` for params
param = strrep(param,'-','_');
if strncmp(param,'_',1) % flag
param = param(2:end); % remove -
eval(sprintf('%s = ~%s;',param,param)); % flip the boolean
else
eval(sprintf('%s = varargin{iv+1} ;',param));
iv = iv + 1; % Extra increment
end
iv = iv + 1;
end
%%%%%%%%%%%%%%%%%%
% Make it into a cell array if it isn't
if ~iscell(cmap)
cmap = num2cell(cmap,2);
end
N = length(cmap);
Xs = linspace(0,1,N+1);
for ix = 1:N
if ix == 1
hold off
else
hold on
end
if ~vert
x0 = Xs(ix); x1 = Xs(ix+1);
y0 = 0; y1 = 1;
else
x0 = 0; x1 = 1;
y0 = Xs(ix); y1 = Xs(ix+1);
end
fill([x0,x1,x1,x0,x0],[y0,y0,y1,y1,y0],cmap{ix},'linestyle', 'none')
end % ix
% Add ticks
ticks = (Xs(2:end) + Xs(1:end-1))/2;
if N>10 || no_label
set(gca,'xtick',[])
set(gca,'ytick',[])
else
if ~vert
set(gca,'xtick',ticks)
set(gca,'xticklabel',1:N)
set(gca,'ytick',[])
else
set(gca,'ytick',ticks)
set(gca,'yticklabel',1:N)
set(gca,'xtick',[])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment