How can I fix the number of ticks in a colorbar, without depending on the values?

17 views (last 30 days)
Is there any way to set the number of ticks in a colorbar? I mean whatever the values are, I want always 5 ticks in the colorbar.
I have tried something like cbr = colorbar L = get(cbr,'YLim'); set(cbr,'YTick',linspace(L(1),L(2),5))
and then using either ceil or floor, but it generates numbers that do not look nice like 1000, 2000, 3000, but instead 1232, 2464, 3696, etc...
Any idea on how to fix this???
  1 Comment
Adam
Adam on 17 Nov 2016
You can either have linearly space ticks or you can define the number of ticks, you can't have both for an arbitrary data range of you want to include the extreme values.
I wrote a function to create axes ticks with values that looked user friendly, but it is 70 lines long and I'm still not always happy with its results, especially if I force it to include the end values.
Ultimately it is just defining the maths you want for your tick values though. If you don't care about spacing or how far they stretch then obviously you can code:
set( cbr, 'YTick', 1000:5000 )
to simply get 5 ticks with nice values on!
I defined my
acceptableTickMultiples = [1 2 2.5 5 7.5 10];
and a desired number of ticks then used some base 10 logarithms on my data range to determine the best set of ticks to fit my constraints, though in my case my desired number of ticks was just advisory and the algorithm aims somewhere close to that.

Sign in to comment.

Answers (1)

Adam
Adam on 17 Nov 2016
figure; hAxes = gca;
imagesc( hAxes, magic( 20 ) )
h = colorbar;
colourRange = caxis( hAxes );
h.Ticks = linspace( colourRange(1), colourRange(end), 5 );
The results look ridiculous in that example, but it does what you require and you can define your 5 ticks in any way you please. Defining a fixed number of human-friendly ticks for an arbitrary data range is always a tricky task though, especially so if you wish to include the extrema of the range.

Categories

Find more on 2-D and 3-D 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!