MATLAB Answers

0

Contourf and colormap limits

Asked by Tomas Levy on 7 Apr 2019
Latest activity Commented on by Cris LaPierre on 8 Apr 2019
Hi there!
Let's say I want to plot this:
contourf(peaks,16)
caxis([-2 2])
colorbar
Now I get:
But I want to show black contour lines only in the caxis limits AND also the color levels in the same limits, i.e. 16 color levels in [-2 2], not just 6 like in the picture.
Any ideas? Thanks

  0 Comments

Sign in to comment.

Products


Release

R2017b

1 Answer

Answer by Cris LaPierre on 8 Apr 2019
Edited by Cris LaPierre on 8 Apr 2019
 Accepted Answer

The problem is your data goes from [-6.5 8]. The 16 contour lines have been drawn for that. Then when you call caxis, you get rid of any color distinction above 2 or below -2 (>2 all have same color, <-2 all have same color). This does not affect where the actual contor lines go, though. Just the range of values used to assign colors.
Instead, specify (in increasing order) the values you want the contour lines at.
Compare the output of these 3 plots
p = peaks;
figure
contourf(p,16)
colorbar
figure
contourf(p,16)
caxis([-2 2])
colorbar
figure
contourf(p,linspace(-2,2,16))
colorbar
I think the last one does what you want.

  4 Comments

Show 1 older comment
Brilliant, that's it. Thank you very much.
Another solution is to append -inf to your list of levels, so that everything below the (now) second value is colored:
figure
contourf(peaks,[-inf linspace(-2,2,16)])
caxis([-2 2])
There is a blog post called On The Edge that gives some more details about how contourf determines what areas to fill.
This is a better approach, since modifying your data just to make it plot as you want will likely have unintended (negative) consequences downstream.
You could use any value less than the overall min of your data.This works for me.
figure
contourf(peaks,[-1000 linspace(-2,2,16)])
caxis([-2 2])

Sign in to comment.