title: How to combine a custom color range with colorbar in MATLAB?
body: <p>I'd like to have a surface plot like the one below, but with a proper colorbar.</p>
  
  <p><img src="https://i.imgur.com/cwtej.jpg" alt="plot without colorbar"></p>
  
  <p>This is my code:</p>
  
  <pre><code>[X,Y,Z] = peaks(30);
  
  [maxval dummy] = max(Z(:));
  [minval dummy] = min(Z(:));
  
  crange = 1.5;
  
  % red, yellow, green
  cmap = [1 0 0; 1 1 0; 0 1 0];  
  colormap(cmap); 
  
  colors = zeros(size(Z));                   
  colors(Z &lt;= -crange) = 1;              % red (1)
  colors(Z &gt; -crange &amp; Z &lt; crange) = 2;  % yellow (2)
  colors(Z &gt;= crange) = 3;               % green (3)
  
  surf(X,Y,Z, colors);
  axis([-3 3 -3 3 -10 10]);
  
  %cbh = colorbar('YGrid','on');    
  %caxis([minval-0.1 maxval+0.1]);
  %set(cbh,'YTick',[minval -crange crange maxval]);
  </code></pre>
  
  <p>So far I had no luck in adding a colorbar where the colors (green,yellow,red) are aligned according to my custom range (green[8 ... 1.5],yellow[1.5 ... -1.5], red[-1.5 ... -6.4]). Instead, when I uncomment the last three lines,
  a colorbar with linearly aligned colors shows up and the colors in my plot are aligned according to the colorbar and not to my custom range.</p>
  
  <p><img src="https://i.imgur.com/h6BE8.jpg" alt="plot with colorbar"></p>
  
  <p>Now, what I'd like to have is that the colors in the colorbar match my custom ticks and that the plot looks like in the first picture.</p>