colorbar to match colors in contourf

As an example: the second example on MATLAB's colorbar documentation page (Add Horizontal Colorbar to a graph) shows a filled contour with a colorbar. However, the colorbar shows many gradients in color, whereas the actual contour shows only 9 different colors. How can I change the colorbar to show only those colors that are actually used in the contour AND how can I change the ticks on the colorbar to indicate the beginning and end of each color interval?
Thank you in advance for the help.

Answers (1)

contourf(peaks)
colormap(parula(9));
% Change this ^ value as how many color reuired max is 64
colorbar('southoutside')
For tick level set the vector accordingly
% This 2nd part of answered belongs to below link
figure_handle=gcf;
cbar_handle=findobj(figure_handle,'tag','Colorbar')
set(cbar_handle,'YAxisLocation','left','YTick',[-5:1:5]);
%...............................................^^^ change and set accordingly
For second part of the question for set up the tick level, you can check here

3 Comments

+1
To add the x ticks at the edges of each discrete color,
contourf(peaks)
nColors = 9;
colormap(parula(nColors));
% Change this ^ value as how many color reuired max is 64
cbh = colorbar('southoutside');
xTick = linspace(min(xlim(cbh)), max(xlim(cbh)), nColors+1);
cbh.XTick = xTick;
190524 090112-Figure 1.jpg
Thank you for the reply. Something seems to not be matching up: in the example data point below, the level is showing as ~3.4, which should have a different color than what is indicated on the colorbar. (There are other data points as well that have different colors than what is indicated in the colorbar).
ContourfExample.png
Old Q&A, but after struggling to work this out myself, you need to explicity set the levels in the contourf call to match the ticks that you define. Otherwise contourf automatically sets it's own level spacing.

Sign in to comment.

Categories

Asked:

SA
on 24 May 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!