4
votes

I have 2d line plot in matlab where each line is colored according to a value. I would like to add a colorbar showing the color that corresponds to these values.

I got a solution to plot the lines according to the value I want, however I can not figure out to get the colorbar correctly. I have been searching on this but I am stuck.

  1. Define an RGB color matrix COL. (N x 3 low red to dark matrix corresponding to equally spaced values 0:1).
  2. Sort the data according to their z value.
  3. Interpolate the COL matrix to get values for all z values, giving the TRUECOL matrix for the lines.
  4. Set the axiscolor-ordering to the TRUECOL matrix and plot the data.

minimalistic example:

% Generate 10 lines of 10 points
x = normrnd(0,1,10,10);
% The corresponding values are 
% Note that these do not have to linearly spaced in real code
z = [0,0.05,0.1,0.11,0.12,0.2,0.4,0.45,0.8,0.9];
% Define colormatrix
COL = [0.996078431372549 0.878431372549020 0.823529411764706;...
   0.937254901960784 0.231372549019608 0.172549019607843;...
   0.403921568627451 0 0.0509803921568627];
% Interpolate the COL matrix to get colors for the data
TRUECOL = interp1(linspace(0,1,3),COL,z,'pchip');
% Set the axis coloring qnd plot the data
set(gcf,'DefaultAxesColorOrder',TRUECOL);
plot(x);
colormap(TRUECOL);
colorbar

I then change the colormap and plot the colobar, however the colors in the colorbar to not correspond to the values z. Is there a way of telling matlab which color corresponds to which value? Looking at the colorbar editor I see that CData must have something to do with it, but I cant find a way to specify that CData should be z.

1
Can you complete your example by adding the change of colormap and plotting of colorbar?Trilarion
The colorbar colors and the line colors look roughly similar. What do you mean by "not correspond"?Trilarion
I changed the z values to make it more clear. To colorbar ranges from 1 to 11 (This can be changed with CLim property). if you open the colobar editor you can see that the colors in the colorbar are linearly mapped in steps of 0.1. I would like to have to colorbar show the actual z values corresponding to the colors in the TRUECOL matrix. Thus the result in the interpolation.MrOperator
Another item in the giant List of Simple Things That MATLAB Cannot Do Automatically" :-/Flyto

1 Answers

2
votes

My understanding is that you want the labels on the colorbar to go from 0 to 1, not 0 to 11. To fix this, use this caxis command. To get finer gradations of colors in the colorbar, you need to more finely interpolate the colormap. Try this:

colormap(interp1(linspace(0,1,size(COL,1)), COL, linspace(0,1,100)));
caxis([0,1]);
colorbar

enter image description here