colorbar to match colors in contourf
Show older comments
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)
KALYAN ACHARJYA
on 24 May 2019
Edited: KALYAN ACHARJYA
on 24 May 2019
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;

SA
on 24 May 2019
Graham Bowen-Davies
on 6 Jan 2022
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.
Categories
Find more on Contour Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!