Search code examples
matlabcolorssurface

Pick a color according to current colormap


My graph contains a number of semi-transparent isosurfaces to visualize density. I choose the color for a range 70:140:

vs=griddata(x,y,z,v,xs,ys,zs,'linear');
for i=70:5:140
  p(i)=patch(isosurface(xs,ys,zs,vs,i));
  isonormals(xs,ys,zs,vs,p(i));
  rd=(i-70)/70;
  set(p(i),'facealpha',0.5);
  set(p(i),'FaceColor',[rd 0 1-rd],'EdgeColor','none'); % set colors
end;
alpha(0.3);

So, here the colors vary from blue (density=70) to red (density=140). How to get a color for a given range from the current colormap?


Solution

  • The documentation explains here how the values are mapped to the colormap using the fix function.

    Here is an example for the range you gave, where the color can be accessed using cmap(index(i),:) for an i in the range rng:

    rng=70:5:140;
    cmap = colormap;
    m = size(cmap,1);
    index = fix((rng-min(rng))/range(rng)*m)+1;
    index(index<1) = 1;
    index(index>m) = m;
    
    % Plot example
    hold on;
    arrayfun(@(i) plot(rng(i),rng(i),'.', ...
        'markersize',30,'color',cmap(index(i),:)),1:length(rng));
    colorbar; hold off;
    

    This example outputs the following plot: image of matlab plot